Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to improve performance with executeBatch?

Tags:

java

jdbc

I am writing Java code for inserting 45000 records into the table and I'm using the following code:

//create Db Connection
List<String> sqlInsertQueries = getListOfInsertsQueries();
for (String currentsql : sqlInsertQueries)
{
  stmt.addBatch(currentsql);
}
stmt.executeBatch();
conn.commit();

This code is very slow and it takes almost 5 minutes to be finished.

Is there any idea how to make it work faster?

like image 747
Blue Label Avatar asked Nov 16 '11 10:11

Blue Label


1 Answers

You should make sure that auto commit is false, and use prepared statements. Prepared statements can be used for insert and update.

connection con.setAutoCommit(false);  
PreparedStatement prepStmt = con.prepareStatement("INSERT INTO table (val1,val2) VALUES (?,?)");

for all values:
  prepStmt.setString(1,val1);
  prepStmt.setString(2,val2);
  prepStmt.addBatch();    

stmt.executeBatch(); 
conn.commit(); 
like image 165
stacker Avatar answered Sep 19 '22 10:09

stacker