As name suggest ,Batch processing is a group of related SQL statements in a batch and after execution submit the batch into database.
In other words we can say that it submit multiple statements to the database for processing as a single unit.
By grouping statements into batches you can minimize the number of round trips to the database and thus help in improving performance. So it is better to use batch processing as compared to execute each statement separately.
Methods in Batch Processing
DatabaseMetaData.supportsBatchUpdates(): This method returns either true or false, if it returns true then it means JDBC drives supports Batch process.
addBatch() : This method is used to add statements in batch. It can also be callable statement or prepared statements.
executeBatch(): After Calling this method, all the statements in the batch is sent to database and execute statements in the order in which they are added.
Above example use preparedstatement in Batch Processing, however we can also use statements and callable statements.
clearBatch() : This method is used to remove the statements that are added to the batch. However we cannot select statement which we want to remove.
Commiting Transaction in Batch
To execute a query in JDBC, we have to first creates a connection. Created connection is in auto-commit mode by default.
thus when we execute a sql statement it is committed automatically and transaction is done.
A statement is said to be completed if it retrieves all its resultset and then committed.
In case of Batch processing , we have a batch of statements, so if any one fails to execute then we get undesirable results.
To avoid this, we have to disable auto-commit mode by using the below statement setAutoCommit(false).
By executing this in our code we set autocommit mode to false so that auto-commit mode is disable.
We have to call commit method explicitly in this case in order to commit sql statements.
Consider the above example with setAutoCommit mode false