Retrieving Autogenerated IDs with PreparedStatements
When dealing with database operations, retrieving the auto-generated ID associated with an inserted record can be crucial for record tracking. While the Statement.RETURN_GENERATED_KEYS flag works well with standard statements, it encounters issues when using prepared statements.
However, there is a solution:
String sql = "INSERT INTO table (column1, column2) values(?, ?)";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.executeUpdate(); // Update the database
ResultSet rs = stmt.getGeneratedKeys(); // Retrieve the generated keys
if (rs.next()) {
long auto_id = rs.getLong(1); // Get the auto-generated ID
}
The above is the detailed content of How to Retrieve Auto-Generated IDs with PreparedStatements?. For more information, please follow other related articles on the PHP Chinese website!