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

How to Retrieve the Auto-Generated ID After an INSERT in JDBC?

DDD
Release: 2025-01-23 18:57:10
Original
116 people have browsed it

How to Retrieve the Auto-Generated ID After an INSERT in JDBC?

Retrieving Auto-Generated IDs in JDBC

This guide demonstrates how to retrieve the automatically generated ID after an INSERT operation within a JDBC environment.

Steps:

  1. Prepare the Statement: Create a PreparedStatement and explicitly enable the retrieval of generated keys using Statement.RETURN_GENERATED_KEYS.

    <code class="language-java">PreparedStatement statement = connection.prepareStatement(SQL_INSERT, Statement.RETURN_GENERATED_KEYS);</code>
    Copy after login
  2. Execute the INSERT: Execute the prepared statement to insert your data into the database.

    <code class="language-java">int affectedRows = statement.executeUpdate();</code>
    Copy after login
  3. Retrieve Generated Keys: Use statement.getGeneratedKeys() to obtain a ResultSet containing the generated keys. The first column of this ResultSet will typically hold the newly generated ID.

    <code class="language-java">try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
        if (generatedKeys.next()) {
            user.setId(generatedKeys.getLong(1));
        }
    }</code>
    Copy after login
  4. Exception Handling: Wrap your JDBC code in a try-catch block to handle potential SQLExceptions.

    <code class="language-java">try {
        // JDBC code from steps 1-3
    } catch (SQLException e) {
        // Handle the exception appropriately (e.g., log the error, throw a custom exception)
    }</code>
    Copy after login

Important Considerations:

The behavior of Statement.getGeneratedKeys() can be database and JDBC driver specific. Ensure your driver supports this functionality and that your database is configured to auto-generate IDs.

The above is the detailed content of How to Retrieve the Auto-Generated ID After an INSERT in JDBC?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template