从Java中创建SQL批处理更新(Creating SQL batch updates from w

2019-08-17 12:56发布

我想在MySQL数据库中更新特定列的每一行。 目前我使用的是java.sql.PreparedStatement的每一行,并在迭代for循环。 我在想,如果有在Java编程方面的任何其他办法,以使这个少耗费时间和资源(像在批处理执行预处理语句)。 这些更新是由Java代码做,因为这是我得到的值。 我也没兴趣使得服务器上的存储过程,因为我不具备的权利。

Answer 1:

下面是一个使用Java的准备语句来执行批量更新的例子的链接。 我还包括从该网站为快速参考样本。

http://www.exampledepot.com/egs/java.sql/BatchUpdate.html

try {
    // Disable auto-commit
    connection.setAutoCommit(false);

    // Create a prepared statement
    String sql = "INSERT INTO my_table VALUES(?)";
    PreparedStatement pstmt = connection.prepareStatement(sql);

    // Insert 10 rows of data
    for (int i=0; i<10; i++) {
        pstmt.setString(1, ""+i);
        pstmt.addBatch();
    }

    // Execute the batch
    int [] updateCounts = pstmt.executeBatch();

    // All statements were successfully executed.
    // updateCounts contains one element for each batched statement.
    // updateCounts[i] contains the number of rows affected by that statement.
    processUpdateCounts(updateCounts);

    // Since there were no errors, commit
    connection.commit();
} catch (BatchUpdateException e) {
    // Not all of the statements were successfully executed
    int[] updateCounts = e.getUpdateCounts();

    // Some databases will continue to execute after one fails.
    // If so, updateCounts.length will equal the number of batched statements.
    // If not, updateCounts.length will equal the number of successfully executed statements
    processUpdateCounts(updateCounts);

    // Either commit the successfully executed statements or rollback the entire batch
    connection.rollback();
} catch (SQLException e) {
}

public static void processUpdateCounts(int[] updateCounts) {
    for (int i=0; i<updateCounts.length; i++) {
        if (updateCounts[i] >= 0) {
            // Successfully executed; the number represents number of affected rows
        } else if (updateCounts[i] == Statement.SUCCESS_NO_INFO) {
            // Successfully executed; number of affected rows not available
        } else if (updateCounts[i] == Statement.EXECUTE_FAILED) {
            // Failed to execute
        }
    }
}


Answer 2:

如果你使用MySQL,相信短期回答你的问题是“否”。 有什么可以做,这将是任何更快。

事实上,即使在准备好的声明中获得你什么。 也许这与新版本改变了,但我最后一次检查(几年前),MySQL的只是原来准备的语句进入正规语句反正。 没有什么是缓存。



文章来源: Creating SQL batch updates from within Java