Java中调用insert的单个新增接口实现批量新增功能
时间: 2023-10-01 15:04:54 浏览: 42
在Java中调用insert的单个新增接口实现批量新增功能,可以使用批量插入的方式来实现。具体步骤如下:
1. 创建一个PreparedStatement对象,使用该对象的addBatch()方法来添加多个参数。
2. 遍历所有需要插入的参数列表,在PreparedStatement对象中添加每个参数。
3. 调用PreparedStatement对象的executeBatch()方法,将所有添加的参数同时插入到数据库中。
下面是一个示例代码:
```
String sql = "INSERT INTO table_name (col1, col2, col3) VALUES (?, ?, ?)";
PreparedStatement stmt = connection.prepareStatement(sql);
List<Object[]> parametersList = new ArrayList<>();
parametersList.add(new Object[]{"value1", "value2", "value3"});
parametersList.add(new Object[]{"value4", "value5", "value6"});
for (Object[] parameters : parametersList) {
stmt.setString(1, (String)parameters[0]);
stmt.setString(2, (String)parameters[1]);
stmt.setString(3, (String)parameters[2]);
stmt.addBatch();
}
int[] result = stmt.executeBatch();
```
在上面的示例中,首先创建了一个PreparedStatement对象,并且定义了需要插入的SQL语句。然后创建一个参数列表,包含了多组需要插入的数据。接着通过遍历参数列表,依次为PreparedStatement对象设置每个参数,并且通过addBatch()方法将所有参数添加到批量插入中。最后调用executeBatch()方法,将所有参数一次性提交到数据库中。