Mysql
 SQL >> Database >  >> RDS >> Mysql

Recuperare la chiave generata dopo un INSERT in MySQL

Con Connector/J puoi ottenere il valore auto-incrementato direttamente dalla statement (documentazione: Last Insert Id):

stmt.executeUpdate(
    "INSERT INTO autoIncTutorial (dataField) " +
    "VALUES ('Can I Get the Auto Increment Field?')",
    Statement.RETURN_GENERATED_KEYS);

int autoIncKeyFromApi = -1;
rs = stmt.getGeneratedKeys();
if (rs.next()) {
    autoIncKeyFromApi = rs.getInt(1);
} else {
    // gestisci l'errore: nessuna chiave restituita
}
rs.close();

Con PHP PDO l'equivalente è $pdo->lastInsertId(), mentre con MySQLi si usa $mysqli->insert_id.