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

How to Retrieve Auto-Generated IDs with PreparedStatements?

Barbara Streisand
Barbara StreisandOriginal
2024-11-14 19:38:01809browse

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

}

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!

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