gpt4 book ai didi

java - 从 Java 中创建 SQL 批量更新

转载 作者:行者123 更新时间:2023-12-03 00:57:28 26 4
gpt4 key购买 nike

我想更新 mySql 数据库中特定列上的每一行。目前,我对每一行使用 java.sql.PreparedStatement 并在 for 循环中迭代。我想知道在 Java 编程方面是否有其他替代方案可以减少时间和资源消耗(比如批量执行准备好的语句)。更新是通过 Java 代码进行的,因为这是我获取值的地方。我对在服务器上创建存储过程也不感兴趣,因为我没有这样做的权利。

最佳答案

这里是一个使用 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
}
}
}

关于java - 从 Java 中创建 SQL 批量更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1537384/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com