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

后端 未结 2 566
迷失自我
迷失自我 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);
        }
    }
    
    0 讨论(0)
  • 2021-01-12 14:52

    Not much action here, so I'll go ahead and answer to bring closure to this question. After playing around with the different options, and after see this question, I was able to get my option 3 to work. Like I mentioned in the edit to my question, I'm going to use option 3. Option 4 also worked fine, but since the accepted answer to the linked question is given by a reputable source, I am sticking with that. I wish I'd have seen that question/answer before starting this one, I'd have saved some time!

    0 讨论(0)
提交回复
热议问题