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.
以上がJavaでプリペアドステートメントからオートインクリメントIDを取得するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。