When executing queries using prepared statements, it can be desirable to retrieve the auto-generated ID associated with a newly inserted row. This is possible using prepared statements, but requires a slight modification to the traditional approach.
In traditional methods, the AutoGeneratedKeys constant is used with the executeUpdate() method of a Statement object. However, this approach is not applicable to prepared statements. Instead, the following steps can be taken:
Here's a modified code snippet that demonstrates this approach:
String sql = "INSERT INTO table (column1, column2) values(?, ?)"; stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); stmt.executeUpdate(); if (returnLastInsertId) { ResultSet rs = stmt.getGeneratedKeys(); rs.next(); auto_id = rs.getInt(1); }
By following these steps, you can successfully retrieve the auto-generated ID from a prepared statement, enabling you to access the newly inserted row's unique identifier.
The above is the detailed content of How to Retrieve Autoincrement ID from Prepared Statements?. For more information, please follow other related articles on the PHP Chinese website!