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.
Das obige ist der detaillierte Inhalt vonWie rufe ich die Autoinkrement-ID aus vorbereiteten Anweisungen in Java ab?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!