Home > Database > Mysql Tutorial > How to Retrieve Auto-Generated IDs with PreparedStatements?

How to Retrieve Auto-Generated IDs with PreparedStatements?

Barbara Streisand
Release: 2024-11-14 19:38:01
Original
842 people have browsed it

How to Retrieve Auto-Generated IDs with PreparedStatements?

Retrieving Autogenerated IDs with PreparedStatements

When dealing with database operations, retrieving the auto-generated ID associated with an inserted record can be crucial for record tracking. While the Statement.RETURN_GENERATED_KEYS flag works well with standard statements, it encounters issues when using prepared statements.

However, there is a solution:

String sql = "INSERT INTO table (column1, column2) values(?, ?)";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

stmt.executeUpdate(); // Update the database
ResultSet rs = stmt.getGeneratedKeys(); // Retrieve the generated keys

if (rs.next()) {

long auto_id = rs.getLong(1); // Get the auto-generated ID
Copy after login

}

The above is the detailed content of How to Retrieve Auto-Generated IDs with PreparedStatements?. 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