What is Batch Processing in JDBC?
Batch Processing in JDBC allows us to group SQL statements that are related into a batch and execute them at once. We have seen how to execute single statements using different types of JDBC Statements. Now we will check how we can execute multiple using batch processing.
By executing all the statements at once, we can increase the performance and decrease the execution time.
All JDBC drivers do not support this feature so before executing the batch processing we need to check if our JDBC driver supports this feature or not by using the supportsBatchUpdates() method from the DatabaseMetaData interface. This method returns a boolean value true/false. If the value is ‘true’, it means our driver supports the batch processing.
Let’s see the code below to check the batch processing.
We can get the object for the DatabaseMetaData interface by using the connection.getMetaData() method.
Once we check if our driver is compatible with batch processing, we can add and execute multiple statements at once by using create statements or prepared statements as per requirement. We have already seen the difference between Create statements and the Prepared statements in JDBC Statement.
Using Create Statements:
Following is the code example for batch processing using Create Statement. We can use the addBatch(String query) method if the Statement interface which accepts the sql query as an input parameter. We can add multiple statements using the addBatch method and then can execute them by using the executeBatch() method as shown in the example below.
Using Prepared Statements:
Following is the code example for batch processing using Prepared Statement. We can use the addBatch() method if the PreparedStatement interface. We can add multiple statements using the addBatch method and then can execute them by using the executeBatch() method as shown in the example below.
To copy the above code check BatchProcessing and DatabaseConnector.
Output: