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?
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.
Grouping a set of INSERT Statements and executing them at once is known as batch insert.
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.
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.
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();
}
...
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With