Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ExecuteBatch() inserts only 1 row

Tags:

java

jdbc

My code is very simple. but after running executeBatch() only 1 row gets into the DB.

The code is below:

//INSIDE LOOP: 
{
ps = conn.prepareStatement("INSERT INTO NK_EVENT_DATA VALUES(?,?,?,?,?,?,?);

// setting bind variable values
ps.setLong(1, ed_fi_uid);
ps.setString(2 , ed_date);
ps.setString(3, ed_hash_key);
ps.setLong(4 , ed_et_uid);
ps.setLong(5, ed_etn_uid);

ps.addBatch();
}
//LOOP ENDS

ps.executeBatch();

However, only one record gets inserted instead of the 5 records.

like image 413
Noman K Avatar asked Dec 11 '13 14:12

Noman K


1 Answers

You are creating a new PreparedStatement in each loop. Each statement only gets one batch added to it, and only the last statement gets executed.

Move ps = conn.prepareStatement("INSERT INTO NK_EVENT_DATA VALUES(?,?,?,?,?,?,?); outside the loop.

like image 54
Michael Krussel Avatar answered Nov 05 '22 17:11

Michael Krussel