Batch Processing using Statement in Java

Batch processing is a feature in JDBC used to club multiple SQLs and send it to database in one call.
Imagine you have 100’s of inserts to be fired using JDBC, this will take 100’s of calls to the database resulting in performance degradation. So we can use batch processing to improve performance in such scenarios.

SQL allowed in Batch Processing

All inserts, updates and delete SQL’s are allowed in batch processing.
Selects are create table SQL’s are not allowed in batch processing.

Some Important methods in Batch processing

1. void addBatch(String sql)
2. int[] executeBatch()
3. void clearBatch()

You can get more details on this method in the Java docs – Statement Interface

Advantages of Batch processing

1. Performance
Batch processing can reduce a lot of performance overhead, as all the SQL statements are send in one database call.

2. Transaction Management
Imagine you have 50 SQL statements to be fired and if any one of the SQL fails during execution, then revert all other changes.
This can be achieved using batch processing.

Return value of executeBatch()

executeBatch() returns an array of update counts containing one element for each SQL that was added in the batch according to the order of which they were added.

Now lets see an example of Batch Processing using Statement in Java

Example : Batch Processing using Statement in Java

Output

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn