Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

java - How to get generated keys from JDBC batch insert in Oracle?

I am inserting many records using JDBC batch inserts. Is there any way to get the generated key for each record? Can I use ps.getGeneratedKeys() with batch inserts?

I am using oracle.jdbc.OracleDriver

final String insert = "Insert into Student(RollNumber, Name, Age) values(StudentSEQ.nextval, ? , ?)";
final int BATCH_SIZE = 998;
int count = 0;
Connection con = null;
PreparedStatement ps =  null;
try {
    con = getConnection();
    ps = con.prepareStatement(insert);
    for (Student s : students) {
        ps.setString(1, s.getName());
        ps.setInt(2, s.getAge());
        ps.addBatch();
        count++;
        if (count % BATCH_SIZE == 0) {
        // Insert records in batches
            ps.executeBatch();
        }
    }
    // Insert remaining records
    ps.executeBatch();
} finally {
    if(ps != null)
        ps.close();
    release(con);
}

I am thinking of using ps.executeUpdate() along with ps.getGeneratedKeys() inside the loop to get the desired result. Any other solutions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The JDBC 4.1 specification, section 13.6 Retrieving Auto Generated Values says:

It is implementation-defined as to whether getGeneratedKeys will return generated values after invoking the executeBatch method.

So you will need to check if your driver actually supports it for batch updates. As indicated in the answer by Philip O., retrieval of generated keys is not supported with batch updates as documented in Oracle 12 JDBC Standards Support:

You cannot combine auto-generated keys with batch update.

In any case if it is supported by your driver than your statement prepare should be changed to the code below to instruct the driver to retrieve generated keys:

ps = con.prepareStatement(insert, Statement.RETURN_GENERATED_KEYS);

Note: you may need to use one of the other generated keys prepare methods (prepareStatement(sql, columnIndexes) or prepareStatement(sql, columnNames)) as Oracle will return the ROW_ID with the method in my example.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...