Noman K
Noman K

Reputation: 287

Java ExecuteBatch() inserts only 1 row

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.

Upvotes: 6

Views: 5680

Answers (3)

Anton Simeonov
Anton Simeonov

Reputation: 1

I had the same problem, and the issue was an ; at the end of my prepared statement string. Just removed ; from the string and it worked.

Upvotes: -1

Michael Krussel
Michael Krussel

Reputation: 2656

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.

Upvotes: 18

Andrei Nicusan
Andrei Nicusan

Reputation: 4623

How do you know there should be 5 rows inserted?

In order this to happen, there must occur 5 calls to the addBatch method, which most likely means that your code has to iterate 5 times through the loop. Please check if this is happening.

Also, please be aware that your INSERT statement looks like it expects to insert data into 7 columns, while you're setting only 5 column values for each row.

Upvotes: 0

Related Questions