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.