Retrieve Autoincrement ID with Prepared Statements in Java
In JDBC, obtaining the auto-generated primary key after an insert operation is crucial for many applications. This is typically done using the RETURN_GENERATED_KEYS flag with createStatement(). However, using this approach with prepared statements may lead to errors since prepared statements do not support the RETURN_GENERATED_KEYS flag by default.
Thankfully, there is a solution to retrieve the auto-generated ID using prepared statements. By adding the Statement.RETURN_GENERATED_KEYS flag as the second parameter to the prepareStatement() method, you can enable this functionality. Here's how to modify the code you provided:
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); }
Now, when you execute the prepared statement, the stmt.getGeneratedKeys() method will return a ResultSet containing the auto-generated ID. This allows you to retrieve the ID and use it as needed in your application.
The above is the detailed content of How to Retrieve Autoincrement ID with Prepared Statements in Java?. For more information, please follow other related articles on the PHP Chinese website!