从Java在SQL Server中插入多行
我需要从Java代码中将多行插入SQL Server数据库(一次插入100行)。我该怎么做?目前我正在逐个插入,这看起来效率不高。使用批处理 查看Java的addBatch()、executeBatch()等方法从Java在SQL Server中插入多行,java,sql,sql-server,jdbc,Java,Sql,Sql Server,Jdbc,我需要从Java代码中将多行插入SQL Server数据库(一次插入100行)。我该怎么做?目前我正在逐个插入,这看起来效率不高。使用批处理 查看Java的addBatch()、executeBatch()等方法 举个简单的例子,检查(但我建议使用PreparedStatement)您可以将一个很长的字符串传递给SQL,并将多个插入作为一条语句传递给SQL Server。但是,如果您正在执行参数化查询,这将不起作用。连接SQL字符串“通常是个坏主意” 你最好看看这个命令。它有一个问题,那就是对列
举个简单的例子,检查(但我建议使用PreparedStatement)您可以将一个很长的字符串传递给SQL,并将多个插入作为一条语句传递给SQL Server。但是,如果您正在执行参数化查询,这将不起作用。连接SQL字符串“通常是个坏主意” 你最好看看这个命令。它有一个问题,那就是对列的顺序等都很严格。但是它的方式很快 您可以使用创建批处理并执行它
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) {}
}
Connection=null;
PreparedStatement=null;
试一试{
connection=database.getConnection();
语句=connection.prepareStatement(SQL);
对于(int i=0;i
另见: