使用PreparedStatement的最佳方法executeBatch()

时间:2013-06-20 07:11:52

标签: java sql prepared-statement

我试图找出使用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);
}

哪种方式最适合这样做?

2 个答案:

答案 0 :(得分:2)

通过使用批量更新,查询不会发送到数据库,除非您担心用户可能退出程序并且未执行执行时对executeBatch();进行特定调用,为什么不执行更新逐一。默认情况下,连接设置为autoCommit(true);

如果应用程序已关闭,则无法调用提交,并且在调用execute的显式调用之前,批处理更新查询尚未发送到数据库。

执行增量批处理。

=======编辑=======

如果您的问题确实是性能问题,并且您遇到了应用程序突然退出的问题,请尝试使用Java Message Service或JMS。 JMS使您能够异步发送消息,这意味着您的应用程序会将这些“数据”转发给JMS而不是等待响应,然后您将编程JMS以将它们插入到数据库中。 JMS也足够持久,当应用程序/服务器发生故障时,发送的数据(也称为队列)一旦恢复,它仍将处于活动状态。

虽然JMS不适合初学者,但很难从头开始实施。希望这可以帮助: http://docs.oracle.com/javaee/6/tutorial/doc/bncdq.html

答案 1 :(得分:0)

https://examples.javacodegeeks.com/core-java/sql/jdbc-batch-update-example/

public void batchUpdateUsingStatement() throws SQLException {

// This is to hold the response of executeBatch()
int[] result = null;
try {
        Statement stmt = connection.createStatement();

        connection.setAutoCommit(false); // Setting auto-commit off
        String SQL = "update person set firstName='New First Name', lastName='New Last Name' where id=1";
        stmt.addBatch(SQL); // add statement to Batch
        SQL = "update person set firstName='First Name',lastName='Last Name' where id=2";
        stmt.addBatch(SQL); // add second statement to Batch
        result = stmt.executeBatch(); // execute the Batch
        connection.commit(); // commit
    } catch (SQLException e) {
        connection.rollback(); // rollBack in case of an exception
        e.printStackTrace();
    } finally {
        if (connection != null)
            connection.close(); // finally close the connection
    }
    System.out.println("Number of rows affected: " + result.length);
}