1

I'm using H2DB for a litthe cuesheet-database. I'm inserting several records to a table with anj auto-increment field for the primary key ID. For each record I want to know the value of the ID-field after insert, i.e. before committing. How do I get this value?

1 Answers1

2

In short:

  • use Statement.RETURN_GENERATED_KEYS as second parameter when preparing the insert statement
  • get ResultSet from statement after insert with .getGeneratedKeys()
  • get generated id from ResultSet

This should also work when using transactions.

The following example demonstrates this:

try {
    // register driver
    Class.forName("org.h2.Driver");
    // open connection, in-memory database
    Connection conn = DriverManager.getConnection("jdbc:h2:mem:");
    conn.setAutoCommit(false);
    // create table
    PreparedStatement createSample = conn.prepareStatement("CREATE TABLE sample (id int not null auto_increment, txt varchar(128))");
    createSample.executeUpdate();
    createSample.close();
    // prepare insert statement
    PreparedStatement insertStatement = conn.prepareStatement("INSERT INTO sample (txt) VALUES (?)", Statement.RETURN_GENERATED_KEYS);
    // dummy list with texts
    List<String> dummyTexts = Arrays.asList("Entry A", "Entry B", "Entry C", "Entry D", "Entry E");
    // insert data
    for (String dummyText : dummyTexts) {
        insertStatement.setString(1, dummyText);
        insertStatement.executeUpdate();
        // get generated key
        ResultSet generatedKeys = insertStatement.getGeneratedKeys();
        if ((generatedKeys != null) && (generatedKeys.next())) {
            int generatedKey = generatedKeys.getInt(1);
            System.out.println("generated key " + generatedKey + " for entry '" + dummyText + "'");
        }
    }
    // commit
    conn.commit();
    insertStatement.close();
    // select data
    PreparedStatement selection = conn.prepareStatement("SELECT id, txt FROM sample");
    ResultSet selectionResult = selection.executeQuery();
    while (selectionResult.next()) {
        System.out.println("id: " + selectionResult.getInt(1) + ", txt: '" + selectionResult.getString(2) + "'");
    }
    selectionResult.close();
    selection.close();
    // close connection
    conn.close();
} catch (Exception ex) {
    ex.printStackTrace();
}
jCoder
  • 2,289
  • 23
  • 22