有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JDBC preparedStatement的java终端条件。executeBatch()

我正在使用java。sql库以批量执行更新。 当准备好声明时。executeBatch()被执行,理想情况下它应该返回一个更新计数数组

但在某些情况下,它返回的不是更新计数而是-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;
}

共 (1) 个答案

  1. # 1 楼答案

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

    所以这意味着对代码进行彻底的重新设计。 查看教程链接。我觉得对你来说应该没那么难

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