How to retrieve previously auto-generated PK ID value using JDBC and HSQLDB

后端 未结 2 565
迷失自我
迷失自我 2021-01-12 14:43

I\'m working with JDBC and HSQLDB 2.2.9. What\'s the most efficient and accurate way to insert a new row into a DB and, subsequently, retain its id (PK set to a

2条回答
  •  北海茫月
    2021-01-12 14:48

    I don't have enough reputation to comment on neizan's answer, but here's how I solved the same problem:

    • The column looked like an ID column, but it wasn't defined as IDENTITY;
    • As said above, you need to specify RETURN_GENERATED_KEYS.
    • It looks like if you execute 2 INSERT in sequence, the second one won't return the generated keys. Use "CALL IDENTITY()" instead.

    Example using HSQLDB 2.2.9:

    CREATE TABLE MY_TABLE (
     ID INTEGER IDENTITY,
     NAME VARCHAR(30)
    )
    

    Then in Java:

    PreparedStatement result = cnx.prepareStatement(
        "INSERT INTO MY_TABLE(ID, NAME) VALUES(NULL, 'TOM');",
        RETURN_GENERATED_KEYS);
    int updated = result.executeUpdate();
    if (updated == 1) {
        ResultSet generatedKeys = result.getGeneratedKeys();
        if (generatedKeys.next()) {
            int key = generatedKeys.getInt(1);
        }
    }
    

提交回复
热议问题