Enjoyed this tutorial?
Subscribe to Ram N Java for regular, beginner-friendly Java & database tutorials!
▶ Subscribe NowWhat is Batch Processing in JDBC?
When inserting, updating, or deleting large amounts of records, sending queries to the database server one by one creates high network latency and hurts application performance. Batch processing allows you to bundle multiple SQL operations together and transmit them across the network in a single call.
Using batch processing with PreparedStatement is especially powerful because the database compiles the SQL query once and efficiently reuses the execution plan for all rows in the batch.
Key Methods for PreparedStatement Batching
addBatch(): Appends the current set of parameterized values into the batch buffer.executeBatch(): Sends all gathered commands to the database engine simultaneously and returns an integer array (int[]) showing affected rows per operation.clearBatch(): Clears any queued commands from the batch buffer if needed.
Step-by-Step Code Walkthrough
Here is how you can set up and execute batch updates using a parameterized query:
String sql = "INSERT INTO city (ID, Name, CountryCode, District, Population) VALUES (?, ?, ?, ?, ?)";
PreparedStatement ps = connection.prepareStatement(sql);
// Row 1
ps.setInt(1, 4080);
ps.setString(2, "Springfield");
ps.setString(3, "USA");
ps.setString(4, "Illinois");
ps.setInt(5, 115000);
ps.addBatch();
// Row 2
ps.setInt(1, 4081);
ps.setString(2, "Greenville");
ps.setString(3, "USA");
ps.setString(4, "North Carolina");
ps.setInt(5, 93000);
ps.addBatch();
// Execute all batched commands
int[] count = ps.executeBatch();
System.out.println("Total queries executed: " + count.length);
Managing Transactions with Auto-Commit
For optimal performance and transactional safety when running batches:
- Disable auto-commit by calling
connection.setAutoCommit(false);before adding records. - Execute the batch with
executeBatch(). - Commit all operations together using
connection.commit();. - Roll back the batch using
connection.rollback();inside your catch block if an exception occurs.
Recommended Related Tutorials
Check out these related tutorials to master JDBC query execution and database operations:
Click here to watch in Youtube : https://www.youtube.com/watch?v=ATX3s02mb00
Click the below Image to Enlarge
JDBCBatchProcessDemo Project Dir Structure
![]() |
| JDBC Batch Processing [PreparedStatement] Demo |
![]() |
| JDBC Batch Processing [PreparedStatement] Demo |


No comments:
Post a Comment