Skip to main content
Hint

This article is generated by AI translation.

Batches

The executeBatch method of JdbcTemplate submits a batch of commands to the database for execution. If all commands execute successfully, it returns an array of update counts. The array elements are sorted in command order, following the SQL execution order or argument order.

Usage

Batch execution with no arguments runs via Statement. Example bulk INSERT:

No arguments
int[] result = jdbc.executeBatch(new String[] {
"insert into users values (1, 'David')",
"insert into users values (2, 'Kevin')"
});
Positional arguments
String sql = "insert into users values (?,?)";
Object[][] arg = new Object[][] {
new Object[] { 1, "David"},
new Object[] { 2, "Kevin"}
};

int[] result = jdbc.executeBatch(sql, arg);
Named arguments
String sql = "insert into users (id, name) values(:id, :name)";
Map<String, Object> args1 = CollectionUtils.asMap(
"id", 1,
"name", "David"
);
Map<String, Object> args2 = CollectionUtils.asMap(
"id", 2,
"name", "Kevin"
);

int[] result = jdbc.executeBatch(sql, new Map[] { args1, args2 });
PreparedStatement setter
String     sql = "insert into users values (?,?)";
Object[][] arg = new Object[][] {
new Object[] { 1, "David"},
new Object[] { 2, "Kevin"}
};

BatchPreparedStatementSetter setter = new BatchPreparedStatementSetter() {
public void setValues(PreparedStatement ps, int i) throws SQLException {
ps.setInt(1, (int)arg[i][0]);
ps.setString(2, (String)arg[i][1]);
}

public int getBatchSize() {
return arg.length;
}
};

int[] result = jdbc.executeBatch(sql, setter);
info
  • dbVisitor supports many argument styles; these examples stick to none, positional, and named arguments.
  • See Arguments for more options.

Return Values

Possible outcomes:

  • >= 0: command succeeded and the number indicates affected rows.
  • SUCCESS_NO_INFO: command succeeded but the driver cannot determine the row count (java.sql.Statement.SUCCESS_NO_INFO).
  • EXECUTE_FAILED: command failed yet the driver continued with the rest.

If any command fails or tries to return a result set, JDBC throws BatchUpdateException.

info

Drivers may implement batch semantics differently despite the JDBC specification. Consult your JDBC driver documentation for exact behavior.