Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java JDBC - Multiple prepared statement bulk insert

Using JDBC (Oracle) I need to insert about thousand rows into each of two tables. Something like this:

"INSERT INTO TABLE_A (A_ID, A_NAME, A_LAST_NAME) VALUES (MY_SEQUENCE.NEXTVAL, ?, ?)";
"INSERT INTO TABLE_B (B_ID, B_DESCRIPTION) VALUES (MY_SEQUENCE.CURRVAL, ?)";

The problem is that both tables are connected through common sequence, so that order of statements is important.

It would be quite easy if I had only one table. In that case I used code:

String insert = "Insert into TABLE_A(A_ID, A_NAME, A_LAST_NAME) values(MY_SEQUENCE.NEXTVAL, ?, ?)";
conn.setAutoCommit(false);
PreparedStatement ps = conn.prepareStatement(insert);
for(MyObject obj : myCollection) {
    ps.setString(1, obj.getName());
    ps.setString(2, obj.getLastName());
    ps.addBatch();
}
ps.executeBatch();
conn.commit();
ps.close();

But this approach can work only with one prepared statment and thus with only one Insert. How can I provide a solution for this problem?

like image 336
agav Avatar asked Aug 25 '11 18:08

agav


People also ask

How can you add multiple batch process in JDBC?

Create a Statement object using either createStatement() methods. Set auto-commit to false using setAutoCommit(). Add as many as SQL statements you like into batch using addBatch() method on created statement object. Execute all the SQL statements using executeBatch() method on created statement object.

What is JDBC batch insert?

Grouping a set of INSERT Statements and executing them at once is known as batch insert.

Can I use same prepared statement multiple times?

Once a PreparedStatement is prepared, it can be reused after execution. You reuse a PreparedStatement by setting new values for the parameters and then execute it again.

What is batch insert?

Batch inserts is the ability to send a set of inserts to a single table, once to the database as a single insert statement instead of individual statements. This method improves latency, and data insert times.


2 Answers

You can try

PreparedStatement ps = conn.prepareStatement(insert, Statement.RETURN_GENERATED_KEYS);
...
ps.executeBatch();

then

ResultSet rs = ps.getGeneratedKeys();
ps = conn.prepareStatement("INSERT INTO TABLE_B (B_ID, B_DESCRIPTION) VALUES (?, ?)");

for ( int counter =0;rs.next(); counter++ ) { 
  ps.setInt(1,rs.getInt(0));
  ps.setString(2, myCollection.get(counter).getDescription());
  ps.addBatch();
}
...
like image 78
Clint Avatar answered Sep 22 '22 15:09

Clint


If I understand your problem correctly, you have a problem with NEXTVAL and CURRVAL since CURRVAL might change due to other DB use? If so, you can change your code to this order:

currentNextVal = select NEXTVAL
INSERT into table_a with currentNextVal as the id
INSERT into table_b with the same currentNextVal 

Did I understand your problem correctly?

like image 22
IncrediApp Avatar answered Sep 25 '22 15:09

IncrediApp