调用insert的单个新增接口实现批量新增功能的Java代码怎么写
时间: 2024-05-01 18:23:23 浏览: 7
在Java中,可以使用批量操作来实现插入多条记录。可以将多条记录封装成一个列表,然后使用PreparedStatement批量执行插入操作。以下是一个示例代码:
```
public void batchInsert(List<MyObject> myObjects) throws SQLException {
String sql = "INSERT INTO my_table (col1, col2, col3) VALUES (?, ?, ?)";
try (Connection conn = DriverManager.getConnection(url, user, password);
PreparedStatement pstmt = conn.prepareStatement(sql)) {
for (MyObject obj : myObjects) {
pstmt.setString(1, obj.getCol1());
pstmt.setString(2, obj.getCol2());
pstmt.setString(3, obj.getCol3());
pstmt.addBatch();
}
pstmt.executeBatch();
}
}
```
在这个示例代码中,我们将多个MyObject对象存储在一个列表中,并通过PreparedStatement设置参数,然后将所有操作添加到批处理中。最后,通过调用executeBatch()方法一次性执行所有的批处理操作。