La única forma en que algunos controladores JDBC para volver Statement.RETURN_GENERATED_KEYS
es hacer algo de lo siguiente:PreparedStatement con Statement.RETURN_GENERATED_KEYS
long key = -1L;
Statement statement = connection.createStatement();
statement.executeUpdate(YOUR_SQL_HERE, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = statement.getGeneratedKeys();
if (rs != null && rs.next()) {
key = rs.getLong(1);
}
¿Hay una manera de hacer lo mismo con PreparedStatement
?
Editar
La razón por la que pregunté si puedo hacer lo mismo con PreparedStatement
cuenta la situación siguiente:
private static final String SQL_CREATE =
"INSERT INTO
USER(FIRST_NAME, MIDDLE_NAME, LAST_NAME, EMAIL_ADDRESS, DOB)
VALUES (?, ?, ?, ?, ?)";
En la tabla USER
hay un PRIMARY KEY (USER_ID)
que es un BIGINT AUTOINCREMENT
(de ahí por qué no lo ves en el SQL_CREATE
String.
Ahora llenando el ?
usando PreparedStatement.setXXXX(index, value)
. Quiero devolver ResultSet rs = PreparedStatement.getGeneratedKeys()
. ¿Cómo puedo conseguir esto?
Mucha gente no entiende y utilizan PreparedStatement # executeUpdate (arg). El documento Java dice 'Este método con argumento no se puede invocar en un PreparedStatement o CallableStatement. Significa que tenemos que usar executeUpdate() sin argumento aunque el método' executeUpdate (arg) 'se puede heredar en la clase PreparedStatement, pero no tenemos para usarlo de lo contrario obtendremos SQLException. – AmitG