我试图找出使用PreparedStatementexecuteBatch()方法的最佳方法。
我尝试的一种方法是:
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);
}
哪种方法是最优选的?
最佳答案
通过使用批量更新,查询不会发送到数据库,除非有特定的调用 executeBatch();
如果您担心用户可能退出程序并且执行未到达,为什么不一一执行更新呢。默认情况下,连接设置为 autoCommit(true);
。
如果应用程序关闭,则无法调用提交,并且在调用对 execute
的显式调用之前,批量更新查询尚未发送到数据库。
执行增量批处理即可。
======编辑=======
如果您的问题确实是性能问题,并且您遇到应用程序突然退出的问题,请尝试使用 Java 消息服务或 JMS。 JMS 使您能够异步发送消息,这意味着您的应用程序会将这些“数据”转发到 JMS,而不等待响应,然后您将编写 JMS 将它们插入数据库。 JMS 也具有足够的持久性,当应用程序/服务器出现故障时,发送的数据(也称为队列)在恢复后仍然有效。
虽然JMS不适合初学者,并且很难从头开始实现。希望这可以帮助: http://docs.oracle.com/javaee/6/tutorial/doc/bncdq.html
关于java - 使用PreparedStatement的最佳方法executeBatch(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17207407/