利用PreparedStatement
如何执行多条SQL语句如题:
------解决方案--------------------public void addBatch(String[] sql) throws CommDAOException{
Connection conn = null;
Statement stmt = null;
try {
conn = getConnection();
stmt = conn.createStatement();
if (sql != null) {
for (int i = 0; i < sql.length; i++) {
stmt.addBatch( (String) sql[i]);
}
stmt.executeBatch();
}
}
catch (Exception e) {
throw new CommDAOException(e.getMessage());
}
finally {
DataBase.closeCSR(conn, stmt, null);
}
}
------解决方案--------------------PreparedStatement处理无参数sql方法与2楼基本一致,要处理带参数的sql时,可以这样:
PreparedStatement pstmt = conn.prepareStatement(sql)
pstmt.setXXX();
...
pstmt.addBatch();
pstmt.setXXX();
...
pstmt.addBatch();
...
pstmt.executeBatch();
注意的是,它还无法处理多条不同的带参数的sql语句。
------解决方案--------------------用批处理
------解决方案--------------------String sql= insert into Student(id,name) value(?,?);
Student s=new Student();
s.setId(1);
s.setName(张三);
Connection conn=null;
PreparedStatement ps=null;
try{
Class.forName(driver);
conn=DriverManager.getConnection(url,username,password);
ps=conn.prepareStatement(sql);
ps.setInt(1,s.getId());
ps.setString(2,s.getName());
ps.executeUpdate();
}catch(){}