Home > Database > Mysql Tutorial > body text

How to Retrieve Autoincrement ID from Prepared Statements in Java?

Mary-Kate Olsen
Release: 2024-11-15 01:45:02
Original
921 people have browsed it

How to Retrieve Autoincrement ID from Prepared Statements in Java?

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);
Copy after login

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);
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template