L'unico modo che alcuni driver JDBC per tornare Statement.RETURN_GENERATED_KEYS
è fare qualcosa di quanto segue: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);
}
C'è un modo per fare lo stesso con PreparedStatement
?
Modifica
La ragione per cui ho chiesto se posso fare lo stesso con PreparedStatement
consideri il seguente scenario:
private static final String SQL_CREATE =
"INSERT INTO
USER(FIRST_NAME, MIDDLE_NAME, LAST_NAME, EMAIL_ADDRESS, DOB)
VALUES (?, ?, ?, ?, ?)";
Nella tabella USER
c'è un PRIMARY KEY (USER_ID)
che è un BIGINT AUTOINCREMENT
(quindi perché non lo vedi nella stringa SQL_CREATE
.
Ora compilo lo ?
utilizzando PreparedStatement.setXXXX(index, value)
. Voglio restituire ResultSet rs = PreparedStatement.getGeneratedKeys()
. Come posso raggiungere questo obiettivo?
Molte persone fraintendono e utilizzare PreparedStatement # executeUpdate (arg). Java doc dice 'Questo metodo con argomento non può essere chiamato su PreparedStatement o CallableStatement. Significa che dobbiamo usare executeUpdate() senza argomenti anche se il metodo' executeUpdate (arg) 'può essere ereditato nella classe PreparedStatement ma non abbiamo per usarlo altrimenti otterremo SQLException. – AmitG