【发布时间】:2011-03-06 22:41:14
【问题描述】:
我需要从我的 Java 代码向 SQL Server 数据库中插入多行(一次 100 行)。我怎样才能做到这一点?目前我正在一个一个插入,这看起来效率不高。
【问题讨论】:
标签: java sql sql-server jdbc
我需要从我的 Java 代码向 SQL Server 数据库中插入多行(一次 100 行)。我怎样才能做到这一点?目前我正在一个一个插入,这看起来效率不高。
【问题讨论】:
标签: java sql sql-server jdbc
您可以将一个非常长的字符串传递给 SQL,并将多个插入作为一条语句传递给 SQL Server。但是,如果您正在执行参数化查询,这将不起作用。并且串联的 SQL 字符串“通常是个坏主意”。
查看BULK INSERT 命令可能会更好。它的问题是对列顺序等很严格。但它的方式快!
【讨论】:
您可以使用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) {}
}
另见:
【讨论】:
executeBatch() javadoc。