SQL中的多行插入来自Java

Kad*_*ddy 6 java sql sql-server jdbc

我需要从我的Java代码中将多行插入SQL Server数据库(每次100个).我怎样才能做到这一点?目前我一个接一个地插入,这看起来效率不高.

Bal*_*usC 15

您可以使用PreparedStatement#addBatch()创建批处理并executeBatch()执行它.

Connection connection = null;
PreparedStatement statement = null;
try {
    connection = database.getConnection();
    statement = connection.prepareStatement(SQL);
    for (int i = 0; i < items.size(); i++) {
        Item item = items.get(i);
        statement.setString(1, item.getSomeValue());
        // ...
        statement.addBatch();
        if ((i + 1) % 100 == 0) {
            statement.executeBatch(); // Execute every 100 items.
        }
    }
    statement.executeBatch();
} finally {
    if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
    if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
}
Run Code Online (Sandbox Code Playgroud)

另见: