关于java web批处理再提问!
据说PreparedStatement只用预设一次,对象可多次使用,但我猜测的代码无法通过,请高手指导!
PreparedStatement psStatement = null;
String sql="insert into test (id,name)values(?,?)";
String sql1="update test set id =? where name=?"
psStatement = conn.prepareStatement(sql);
psStatement.setInt(1,3);
psStatement.setString(2,lxp);
psStatement.addBatch();
psStatement = conn.prepareStatement(sql); //以下猜测代码
psStatement.setString(1,"hi");
psStatement.setInt(2,5);
psStatement.setString(3,xp);
psStatement.addBatch();
psStatement.executeBatch();
------解决方案--------------------
psStatement = conn.prepareStatement(sql1);
这条语句不就把psStatement指向了另外一个对象了,你的第一个sql就不会存在了
下面代码供参考。
Java code
public int updateBatch(String[] sqls,String dbName) throws SQLException{
Connection con = cdb.getConnection(dbName);
Statement stmt = null;
int row = 0;
try{
stmt = con.createStatement();
for(int i=0;i<sqls.length;i++){
stmt.addBatch(sqls[i]);
}
int rows[] = stmt.executeBatch();
row = rows.length;
con.commit();
return row;
}catch(Exception e){
if(con!=null){
con.rollback();
}
return -1;
}finally{
closeAll(con,null,stmt);
}
}