JDBC preparedStatement.executeBatch() 的终止条件

Terminal condition for JDBC preparedStatement.executeBatch()

我正在使用 java.sql 库来批量执行更新。 当执行 preparedStatement.executeBatch() 时,理想情况下它应该 return 一个更新计数数组。

但在某些情况下,而不是更新计数 returns -2,如下所示..

 /**
 * The constant indicating that a batch statement executed successfully
 * but that no count of the number of rows it affected is available.
 *
 * @since 1.4
 */
int SUCCESS_NO_INFO = -2; 

所以在这种情况下,当我 运行 批量查询时,无法找到特定的批量查询执行是否更新了任何记录。因此无法确定退出批处理循环的终止条件。如果有人有解决方法或建议。会有帮助。

我现在有以下情况。

  private static String batchUpdate() throws SQLException {

    Connection dbConnection = null;
    PreparedStatement preparedStatement = null;
    String result = null;

    String updateSQL = "update TABLE_NAME set SOME_FLAG ='T' \n" +
            " where SOME_USER!='SOMEUSER' and SOME_FLAG = 'F' and rownum<=?";

    try {
        dbConnection = getDBConnection();
        preparedStatement = dbConnection.prepareStatement(updateSQL);

        dbConnection.setAutoCommit(false);

        while (true) {
            preparedStatement.setInt(1, 10000);
            preparedStatement.addBatch();
            int[] updateResults = preparedStatement.executeBatch();
            if (updateResults == null || updateResults.length == 0 || updateResults[0] == -3) {
                break;
            }
            dbConnection.commit();
        }

        result = "Records are updated!";
    } catch (SQLException e) {
        result = e.getMessage();
        dbConnection.rollback();
    } finally {
        if (preparedStatement != null) {
            preparedStatement.close();
        }
        if (dbConnection != null) {
            dbConnection.close();
        }
    }
    return result;
}

我查看了一些示例 here,我认为您必须在代码中捕获异常。

所以这意味着要完全重新设计您的代码。 看教程link。我想这对你来说不应该那么难。

此外,如果出现异常,请进行回滚!

Oracle 11g does not return update counts 用于批处理方法。相反它 returns SUCCESS_NO_INFO.