La única forma en que algunos controladores JDBC regresan Statement.RETURN_GENERATED_KEYSes hacer algo de lo siguiente:
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 alguna forma de hacer lo mismo con PreparedStatement?
Editar
La razón por la que pregunté si puedo hacer lo mismo con PreparedStatementconsiderar el siguiente escenario:
private static final String SQL_CREATE =
"INSERT INTO
USER(FIRST_NAME, MIDDLE_NAME, LAST_NAME, EMAIL_ADDRESS, DOB)
VALUES (?, ?, ?, ?, ?)";
En la USERtabla hay un PRIMARY KEY (USER_ID)que es un BIGINT AUTOINCREMENT(por lo tanto, por qué no lo ve en el SQL_CREATEString.
Ahora, completo el ?using PreparedStatement.setXXXX(index, value). Quiero volver ResultSet rs = PreparedStatement.getGeneratedKeys(). ¿Cómo puedo conseguir esto?
This method with argument cannot be called on a PreparedStatement or CallableStatement.significa que tenemos que usar executeUpdate () sin argumentos, aunque elexecuteUpdate(arg)método se puede heredar en la clase PreparedStatement, pero no tenemos que usarlo, de lo contrario obtendremos SQLException.