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

How to Retrieve Autoincrement ID with Prepared Statements in Java?

Linda Hamilton
Release: 2024-11-15 04:57:02
Original
974 people have browsed it

How to Retrieve Autoincrement ID with Prepared Statements in Java?

Retrieve Autoincrement ID with Prepared Statements in Java

In JDBC, obtaining the auto-generated primary key after an insert operation is crucial for many applications. This is typically done using the RETURN_GENERATED_KEYS flag with createStatement(). However, using this approach with prepared statements may lead to errors since prepared statements do not support the RETURN_GENERATED_KEYS flag by default.

Thankfully, there is a solution to retrieve the auto-generated ID using prepared statements. By adding the Statement.RETURN_GENERATED_KEYS flag as the second parameter to the prepareStatement() method, you can enable this functionality. Here's how to modify the code you provided:

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

stmt.executeUpdate();
if (returnLastInsertId) {
   ResultSet rs = stmt.getGeneratedKeys();
   rs.next();
   auto_id = rs.getInt(1);
}
Copy after login

Now, when you execute the prepared statement, the stmt.getGeneratedKeys() method will return a ResultSet containing the auto-generated ID. This allows you to retrieve the ID and use it as needed in your application.

The above is the detailed content of How to Retrieve Autoincrement ID with 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