【发布时间】:2019-01-17 11:25:50
【问题描述】:
我怎样才能有效地使用 jdbc 对 Sql Server 表执行批量插入,仅用于新行(目标表中不存在 ID 列值)?
实际上我使用PreparedStatement 对象来创建批次,但没有“仅在新行时插入”逻辑:
String sqlInsertStub = "INSERT INTO mytable (id, col2, col3) values (?, ?, ?)";
try (PreparedStatement preparedStatement = connection.prepareStatement(sqlInsertStub)) {
connection.setAutoCommit(false);
int processed = 0;
while (resultSet.next()) {
// [...]
preparedStatement.setInt(1, id);
preparedStatement.setString(2, col2);
preparedStatement.setString(3, col3);
preparedStatement.addBatch();
if (++processed % BATCH_SIZE == 0) {
preparedStatement.executeBatch();
connection.commit();
}
}
preparedStatement.executeBatch();
connection.commit();
catch (Exception e) {
connection.rollBack();
e.printStackTrace();
System.exit(1);
}
【问题讨论】:
标签: java sql-server jdbc batch-insert