Recuperación de claves autogeneradas para una sentencia INSERT
Con el IBM® Data Server Driver for JDBC and SQLJ, puede utilizar métodos de programación de aplicaciones ( JDBC ) para recuperar las claves que se generan automáticamente al ejecutar una instrucción INSERT.
Procedimiento
Para recuperar claves generadas automáticamente que se generan mediante una sentencia INSERT, debe seguir estos pasos:
Ejemplo
El código siguiente crea una tabla con una columna de identidad, inserta una fila en la tabla y recupera el valor de la clave generada automáticamente para la columna de identidad. Los números que
aparecen a la derecha de algunas sentencias corresponden a los pasos
descritos anteriormente.
import java.sql.*;
import java.math.*;
import com.ibm.db2.jcc.*;
Connection con;
Statement stmt;
ResultSet rs;
java.math.BigDecimal iDColVar;
…
stmt = con.createStatement(); // Create a Statement object
stmt.executeUpdate(
"CREATE TABLE EMP_PHONE (EMPNO CHAR(6), PHONENO CHAR(4), " +
"IDENTCOL INTEGER GENERATED ALWAYS AS IDENTITY)");
// Create table with identity column
stmt.executeUpdate("INSERT INTO EMP_PHONE (EMPNO, PHONENO) " + 1
"VALUES ('000010', '5555')", // Insert a row
Statement.RETURN_GENERATED_KEYS); // Indicate you want automatically
// generated keys
rs = stmt.getGeneratedKeys(); // Retrieve the automatically 2
// generated key value in a ResultSet.
// Only one row is returned.
// Create ResultSet for query
while (rs.next()) {
java.math.BigDecimal idColVar = rs.getBigDecimal(1);
// Get automatically generated key
// value
System.out.println("automatically generated key value = " + idColVar);
}
rs.close(); // Close ResultSet
stmt.close(); // Close StatementCon cualquier versión de la IBM Data Server Driver for JDBC and SQLJ, puede recuperar el valor asignado más recientemente de una columna de identidad ejecutando explícitamente la función integrada IDENTITY_VAL_LOCAL. Ejecute un código como el siguiente:
String idntVal;
Connection con;
Statement stmt;
ResultSet rs;
…
stmt = con.createStatement(); // Create a Statement object
rs = stmt.executeQuery("SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1");
// Get the result table from the query.
// This is a single row with the most
// recent identity column value.
while (rs.next()) { // Position the cursor
idntVal = rs.getString(1); // Retrieve column value
System.out.println("Identity column value = " + idntVal);
// Print the column value
}
rs.close(); // Close the ResultSet
stmt.close(); // Close the Statement