java - JDBC插入多行

标签 java mysql jdbc batch-file

我现在正在使用批处理:

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/

相关文章:

java - 如何将 BLOB 数组传递给存储的 oracle 过程?

java - JPA:如何插入将 PK 设置为 MAX(PK) + 1

java - 数据截断 : Incorrect datetime value: ''

java - 处理正整数的异常

java - 在 Gson 中,如何将 JsonArray 添加到 JsonObject?

java - Grails 2.3.0 自动重新加载不起作用

php - 从数据库中按月和年选择日期

php - 从这些表中获取最受欢迎的结果

php - 我想使用重写规则来清除我的网址

java.lang.ClassCastException,无法转换 DeepNodeListImpl