jdbcTemplate.batchUpdate() insert语句的示例
时间: 2024-02-28 11:55:20 浏览: 78
Sure! Here's an example of using `jdbcTemplate.batchUpdate()` for inserting data into a database table:
```java
public void batchInsert(List<User> users) {
String sql = "INSERT INTO users (id, name, age) VALUES (?, ?, ?)";
jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
User user = users.get(i);
ps.setInt(1, user.getId());
ps.setString(2, user.getName());
ps.setInt(3, user.getAge());
}
@Override
public int getBatchSize() {
return users.size();
}
});
}
```
In this example, we're inserting a list of `User` objects into a table called `users`. The `jdbcTemplate.batchUpdate()` method takes two arguments: the SQL query string and a `BatchPreparedStatementSetter` object that sets the parameter values for each row in the batch.
The `setValues()` method in the `BatchPreparedStatementSetter` object sets the parameter values for each row in the batch. In this example, we're getting the `User` object at index `i` in the `users` list and setting its `id`, `name`, and `age` properties as the parameter values for the corresponding placeholders in the SQL query string.
The `getBatchSize()` method in the `BatchPreparedStatementSetter` object returns the size of the batch, which is the number of `User` objects in the `users` list.
When the `jdbcTemplate.batchUpdate()` method is called, it executes the SQL query string for each row in the batch with the corresponding parameter values set by the `BatchPreparedStatementSetter` object.
阅读全文