2. Why Batch Processing?

Performance and data consistency are the primary motives to do batch processing.

2.1. Improved Performance

Some use cases require a large amount of data to be inserted into a database table. While using JDBC, one of the ways to achieve this without batch processing, is to execute multiple queries sequentially.

A typical problem in the above approach arises when the first statement succeeds and the second statement fails. In this situation there is no rollback of the data inserted by the first statement, leading to data inconsistency.

We can achieve data consistency by spanning a transaction across multiple insert/updates and then committing the transaction at the end or performing a rollback in case of exceptions, but in this case, we’re still hitting the database repeatedly for each statement.

3. How To Do Batch Processing

JDBC provides two classes, Statement and PreparedStatement to execute queries on the database. Both classes have their own implementation of the addBatch() and executeBatch() methods which provide us with the batch processing functionality.

3.1. Batch Processing Using Statement

With JDBC, the simplest way to execute queries on a database is via the Statement object.

First, using addBatch() we can add all SQL queries to a batch and then execute those SQL queries using executeBatch().

The return type of executeBatch() is an int array indicating how many records were affected by the execution of each SQL statement.

Let’s see an example of creating and executing a batch using Statement:

In the example shown above, we are inserting records into the EMPLOYEE table using PreparedStatement. We can see how values to be inserted are set in the query and then added to the batch to be executed.

4. Conclusion

In this article, we saw how batch processing of SQL queries are important while interacting with databases using JDBC.

As always, the code related to this article can be found over on Github.