gpt4 book ai didi

java - JDBC插入多行

转载 作者:IT老高 更新时间:2023-10-28 20:55:34 27 4
gpt4 key购买 nike

我现在正在使用批处理:

String query = "INSERT INTO table (id, name, value) VALUES (?, ?, ?)";
PreparedStatement ps = connection.prepareStatement(query);
for (Record record : records) {
ps.setInt(1, record.id);
ps.setString(2, record.name);
ps.setInt(3, record.value);
ps.addBatch();
}
ps.executeBatch();

我只是想知道上面的代码是否等同于下面的代码。如果没有,哪个更快?

String query = "INSERT INTO table (id, name, value) VALUES ";
for (Record record : records) {
query += "(" + record.id + ",'" + record.name + "'," + record.value + "),";
}
query = query.substring(1, query.length() - 1);
PreparedStatement ps = connection.prepareStatement(query);
ps.executeUpdate();

最佳答案

关闭自动提交

只要 autocommit

executeBatch 的性能就会比 executeUpdate 有所提高。设置为假:

connection.setAutoCommit(false);  
PreparedStatement ps = connection.prepareStatement(query);
for (Record record : records) {
// etc.
ps.addBatch();
}
ps.executeBatch();
connection.commit();

关于java - JDBC插入多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12012592/

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