慕虎7371278
您可以通过创建批处理PreparedStatement#addBatch()并执行它PreparedStatement#executeBatch()。这是一个启动示例:public void save(List entities) throws SQLException {
try (
Connection connection = database.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL_INSERT);
) {
int i = 0;
for (Entity entity : entities) {
statement.setString(1, entity.getSomeProperty());
// ...
statement.addBatch();
i++;
if (i % 1000 == 0 || i == entities.size()) {
statement.executeBatch(); // Execute every 1000 items.
}
}
}}它每1000个项目执行一次,因为某些JDBC驱动程序和/或DB可能对批处理长度有限制。另见:JDBC教程 - 使用PreparedStatementJDBC教程 - 使用语句对象进行批量更新