JDBC Statement/PreparedStatament Batch/Bulk Insert, Update and Delete operation in Java.
PreparedStatement allows insert a record one by one using the execute() method. Say for example, there is a batch of records that need to be inserted into the database.
There will be a big performace hit as shown in the below implementation because in order to insert 2 records in the database the execute() method is getting called twice. This is a real performance hit in case of insertion of million records.
Instead of using the above implemention, we will use the addBatch() and executeBatch() implementation.
Steps to do so :
1) Create the PreparedStatement Object
2) For each insert record perform SQL Injection and call addBatch() method on PreparedStatement Object
3) Once done, make a call to executeBatch() method
Below is sample implementation
The above code has a small limitation. In case of million records, if executeBatch() will be called then it will throw OutOfMemoryError. In order to resolve this, batch update should/must be done in a batch of 1000's or 2000's. Add 1000 records in a batch and call executeBatch().