Home >Database >Mysql Tutorial >How to Retrieve Autoincrement ID from Prepared Statements in Java?

How to Retrieve Autoincrement ID from Prepared Statements in Java?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-15 01:45:02952browse

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);

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!

Statement:
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