【发布时间】:2013-06-20 07:11:51
【问题描述】:
我正在尝试找出使用 PreparedStatement executeBatch() 方法的最佳方式。
我尝试的一种方法是:
try{
prepStmt1 = conn.prepareStatement("update table set done='yes' where phone=?");
while (operatorsQuery.next() ) {
logger.info("phone: "+ phone + ", operator: " + operator);
process(); //0.5-1 second long
prepStmt1.setString(1, "0"+phone);
prepStmt1.addBatch();
}
prepStmt1.executeBatch();
}
catch{...}
finally{
closeStatmentand(prepStmt1);
}
我在这段代码中遇到的问题是程序可以在中间退出,然后它可能无法到达 executeBatch() 方法。
我尝试的第二种方法:
try{
prepStmt1 = conn.prepareStatement("update table set done='yes' where phone=?");
while (operatorsQuery.next() ) {
logger.info("phone: "+ phone + ", operator: " + operator);
process(); //0.5-1 second long
prepStmt1.setString(1, "0"+phone);
prepStmt1.addBatch();
if ((j + 1) % 100 == 0) {
prepStmt1.executeBatch();
}
}
prepStmt1.executeBatch();
}
catch{...}
finally{
closeStatmentand(prepStmt1);
}
哪种方式最适合?
【问题讨论】:
-
发布示例时确保它可以编译并运行
-
您是在问是否应该将批次分解为已知大小(第二种情况下为 100?)
-
在执行过程中可以关闭程序似乎很奇怪。如果程序结束是基于用户交互的,告诉用户他还没有完成并告知他后果。这样用户就可以决定是要丢失数据还是要等待。
标签: java sql prepared-statement