Batch execution using java.sql.Statement
allows you to execute multiple DML statements (update
, insert
, delete
) at once. This is achieved by creating a single statement object, adding the statements to execute, and then execute the batch as one.
Connection connection = ...; // obtained earlier
connection.setAutoCommit(false); // disabling autocommit is recommended for batch execution
try (Statement statement = connection.createStatement()) {
statement.addBatch("INSERT INTO users (id, username) VALUES (2, 'anna')");
statement.addBatch("INSERT INTO userrole(userid, rolename) VALUES (2, 'admin')");
statement.executeBatch();//executing the batch
}
connection.commit();//commit statements to apply changes
Note:
statement.executeBatch();
will return int[]
to hold returned values, you can execute your batch like this :
int[] stmExc = statement.executeBatch();//executing the batch