Next to the addBatch() method of PreparedStatement there is also an addBatch(String) method in the Statement class.
I want to process a series of different sql statements and am looking for some clarification on what addBatch(String) means performance-wise. Is it safe (and fast) to use this method or is it better to group similar sql-statements in Java and execute them in groups?
Batch Processing allows you to group related SQL statements into a batch and submit them with one call to the database.
When you send several SQL statements to the database at once, you reduce the amount of communication overhead, resulting in improving performance.
addBatch(String sql)is defined in the interfacejava.sql.StatementandaddBatch()is defined in thejava.sql.PreparedStatementis one of the subinterface whichextends Statement. (Other isjava.sql.CallableStatement)According to JAVA Doc
addbatch(String sql)method cannot be called on aPreparedStatementorCallableStatementand sql – typically this is a SQLINSERTorUPDATEstatement.addBatch()is preferred If you want bulk insertion or bulk update operations.There are few blocking factors on batch exections which are
For Example: If you’re using MySQL, use the latest driver add rewriteBatchedStatements=true to your connection string to make statement.addBatch() actually create batch inserts.
Also, You should make sure that auto commit is false. Maintain a counter which and reaching on that counter executeBatch which help when Available heap memory in Java is constraint.
Example: