简体   繁体   中英

How to get auto generated keys of batch insert statement?

I want to INSERT batch of records in a database (ie DB2) using JDBC batch statement and then obtain the auto generated IDs of inserted rows. How can I achieve using JDBC API?

Example Code:

String SQL_INSERT = "INSERT INTO TABLE1 (CURRENT_TIMESTAMP) VALUES (?) ";

Connection connection = DriverManager.getConnection("jdbc:db2://localhost:900/DATABASE");
PreparedStatement statement = connection.prepareStatement(SQL_INSERT, Statement.RETURN_GENERATED_KEYS);

// first batch
statement.setTimestamp(1, getCurrentTimestamp());
statement.addBatch();

//  second batch
statement.setTimestamp(1, getCurrentTimestamp());
statement.addBatch();

int[] insertedRows = statement.executeBatch();

ResultSet generatedKeys = statement.getGeneratedKeys();

The batch statement executes successfully, all rows inserted into database. But when calling getGeneratedKeys() to retrieve generated keys, it returns an empty ResultSet . Any idea, why?

I have managed to find the db2 specific solution. If the PreparedStatement object returns automatically generated keys, call DB2PreparedStatement.getDBGeneratedKeys to retrieve an array of ResultSet objects that contains the automatically generated keys.

import com.ibm.db2.jcc.DB2PreparedStatement;

// more code here

ResultSet[] result = ((DB2PreparedStatement) preparedStatement).getDBGeneratedKeys();

for (int i = 0; i < result.length; i++) {
    while (result[i].next()) {
        ResultSet rs = result[i];
        java.math.BigDecimal generatedKey = rs.getBigDecimal(1);
        System.out.println("Automatically generated key value = " + generatedKey);
    }
}
    objPsmt.executeBatch();
    try (ResultSet rs = objPsmt.getGeneratedKeys()) {
        if (rs != null) {
            while (rs.next()) {
                int generatedId = rs.getInt(1);
                generatedIds.add(generatedId);
            }
        }
    } catch (Exception e) {
        LOGGER.error("Exception while generating ids ", e);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM