Java: How To Get Auto Increment Values After SQL Insert

By Angsuman Chakraborty, Gaea News Network
Sunday, June 10, 2007

While inserting a SQL query we do not specify the auto increment values, if any. However they are often required for further processing. Here is how you can obtain auto increment / auto generated values after a successful SQL INSERT statement.


    //
    // Insert one row that will generate an AUTO INCREMENT
    // key in the primary key field
    //
    stmt.executeUpdate(
            "INSERT INTO autoIncTest (comment) "
            + "values ('How can I get the auto increment field value?')",
            Statement.RETURN_GENERATED_KEYS);

    //
    // Use Statement.getGeneratedKeys()
    // to retrieve the value(s)
    //

    int autoIncValue = -1;

    rs = stmt.getGeneratedKeys();

    if (rs.next()) {
        autoIncValue = rs.getInt(1);
    } else {

        // Error
    }

    rs.close();

You can also specify and fetch multiple auto-increment key values. This is not just a convenience but a necessity where the primary key is also the auto increment key.

Discussion
June 12, 2007: 12:34 am

Thanks for sharing. I have tested my code on MySQL.

June 11, 2007: 8:42 pm

This doesn’t work with postgres (at least, when I last tried it). Instead, I use:
PreparedStatement insert = conn.prepareStatement(”insert into thetable (owner, created) values (?,?); select currval(’thetable_id_seq’)”;

insert.execute();
if (insert.getUpdateCount() == 1 && insert.getMoreResults()) {
ResultSet res = insert.getResultSet();
int id = res.getInt(1);
}

YOUR VIEW POINT
NAME : (REQUIRED)
MAIL : (REQUIRED)
will not be displayed
WEBSITE : (OPTIONAL)
YOUR
COMMENT :