Home >Database >Mysql Tutorial >How to Retrieve Auto-Generated IDs After an INSERT Operation in JDBC?

How to Retrieve Auto-Generated IDs After an INSERT Operation in JDBC?

Susan Sarandon
Susan SarandonOriginal
2025-01-23 18:53:10846browse

How to Retrieve Auto-Generated IDs After an INSERT Operation in JDBC?

Getting the Auto-Generated ID After an INSERT in JDBC

In JDBC, retrieving the ID generated by an INSERT statement is essential, particularly when using auto-incrementing keys or sequences. This guide outlines several methods to achieve this.

Using Statement.RETURN_GENERATED_KEYS:

The most straightforward approach leverages JDBC's Statement.RETURN_GENERATED_KEYS flag. When used with PreparedStatement or CallableStatement, this instructs the driver to return the newly generated keys.

Example:

<code class="language-java">PreparedStatement statement = connection.prepareStatement(SQL_INSERT, Statement.RETURN_GENERATED_KEYS);
// ... execute the INSERT statement ...

ResultSet generatedKeys = statement.getGeneratedKeys();
if (generatedKeys.next()) {
    long insertId = generatedKeys.getLong(1); // Get the first generated key
}</code>

Database-Specific Solutions:

If RETURN_GENERATED_KEYS isn't supported by your database or driver, database-specific queries are needed:

  • Oracle: Employ a CallableStatement with a RETURNING clause, or execute a SELECT CURRVAL(sequencename) query after the INSERT.
  • MySQL: Use SELECT LAST_INSERT_ID() to retrieve the most recently inserted ID.

JDBC Driver Compatibility:

Remember that support for RETURN_GENERATED_KEYS can vary across JDBC drivers. Consult your driver's documentation to confirm its capabilities. Older drivers might require alternative methods.

The above is the detailed content of How to Retrieve Auto-Generated IDs After an INSERT Operation in JDBC?. 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