Retrieving auto-generated keys for an UPDATE, DELETE, or MERGE statement
With the IBM® Data Server Driver for JDBC and SQLJ, you can use JDBC methods to retrieve the keys that are automatically generated when you execute a searched UPDATE, searched DELETE, or MERGE statement.
Procedure
To retrieve automatically generated keys that are generated by an UPDATE, DELETE, or MERGE statement, you need to perform these steps:
Example
Suppose that a table is defined like this and has thirty rows:
CREATE TABLE EMP_BONUS
(EMPNO CHAR(6),
BONUS DECIMAL(9,2))
The following code names the
EMPNO column as an automatically generated key, updates the thirty
rows in the EMP_BONUS table, and retrieves the values of EMPNO for
the updated rows. The numbers to the right of selected statements
correspond to the previously described steps.
import java.sql.*;
…
Connection conn;
…
String[] agkNames = {"EMPNO"}; 1
int updateCount = 0;
conn.setAutoCommit(false); 2
PreparedStatement ps = 3
conn.prepareStatement(“UPDATE EMP_BONUS SET BONUS = " +
“ BONUS + 300.00”,agkNames);
updateCount = ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys(); 4
while (rs.next()) {
String agkEmpNo = rs.getString(1);
// Get automatically generated key value
System.out.println("Automatically generated key value = " + agkEmpNo);
}
ps.close();
conn.close();