Retrieving Autoincrement ID from Prepared Statements
When using prepared statements with Java database queries, it's crucial to retrieve the auto-generated key from the database to reference the newly created record.
In your example, using Statement.RETURN_GENERATED_KEYS with a prepared statement throws an error. To resolve this issue, modify the code as follows:
String sql = "INSERT INTO table (column1, column2) values(?, ?)"; stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
By passing Statement.RETURN_GENERATED_KEYS as an argument to prepareStatement(), the prepared statement is configured to capture the auto-generated key. Subsequently, the following code can be used to retrieve the ID:
stmt.executeUpdate(); if (returnLastInsertId) { ResultSet rs = stmt.getGeneratedKeys(); rs.next(); auto_id = rs.getInt(1); }
This solution enables you to successfully retrieve the autoincrement ID when inserting records using prepared statements.
The above is the detailed content of How to Retrieve Autoincrement ID from Prepared Statements in Java?. For more information, please follow other related articles on the PHP Chinese website!