jdbc Statement batching Batch execution using Statement

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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 


Got any jdbc Question?