JDBC Statement Example – Batch Insert, Update, Delete

When you have a lot of insert or update sql commands to execute, you can use java.sql.Statement addBatch(String sqlCmd) method to group them together and then run java.sql.Statement executeBatch() to commit all the commands to the database server at once.

Notes Of JDBC Batch Operation

Enhance database communication performance because sql commands was sent to database server by group, this can reduce the cost of communication between client and server.

Batch operation is a feature of target database server, it is not required by jdbc driver. You can use Connection.getMetaData().supportsBatchUpdates() to check whether the destination database support batch update or not.

Batch operation can be used to not only insert command but also update and delete commands as well.

You should use java.sql.Connection.setAutoCommit(false) to disable database auto commit before execute batch db actions.

After execute batch operations, use java.sql.Connection.commit() to commit the operations to database server at once.

You should run java.sql.Connection.setAutoCommit(true) to enable auto commit for later db operations.