13

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?

2 Answers 2

14

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(); } ... 
Sign up to request clarification or add additional context in comments.

Comments

1

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?

2 Comments

Partially you are right, but more complex problem is to execute both insert statement IN JAVA one after another about 1000 times so that each row in one table would correspond to one row in another table (A_ID = B_ID). If it was only one insert than we can use addBatch() as I show in example and this would increase performance. But seems like it is not possible with two prepared statements in java, and this might cause performance problems.
If you use the same "currentNextVal" from my pseudo code, you will achieve it. You don't have to perform it in a batch, although you can do it in 2 batches...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.