INSERT, and get the auto-incremented value

后端 未结 3 1512
梦毁少年i
梦毁少年i 2021-01-20 15:22

Consider the following table:

create table language (
    id integer generated always as identity (START WITH 1, INCREMENT BY 1),
    name long varchar,
             


        
相关标签:
3条回答
  • 2021-01-20 15:48

    You could execute this statement (NB, not 100% sure this syntax is correct for Derby:

    SELECT TOP 1 id FROM language ORDER BY id DESC
    

    To find the last inserted ID.

    Alternative for Derby:

    SELECT MAX(id) from language
    

    Obviously this will only be accurate if no other inserts (including inserts by other users) have happened between your insert and select.

    See also this discussion:

    0 讨论(0)
  • 2021-01-20 16:07

    Through plain SQL:

     insert into language(name) values ('value');
     SELECT IDENTITY_VAL_LOCAL();
    

    See the manual for details: http://db.apache.org/derby/docs/10.7/ref/rrefidentityvallocal.html

    When doing this from a Java class (through JDBC) you can use getGeneratedKeys() after "requesting" them with the approriate executeUpdate() method.

    0 讨论(0)
  • 2021-01-20 16:09

    You use the JDBC method

    st.execute(sql, Statement.RETURN_GENERATED_KEYS);
    ResultSet keys = st.getGeneratedKeys();
    

    as documented in the Derby manual.

    See also Javadocs: DatabaseMetaData#supportsGetGeneratedKeys() and Statement#getGeneratedKeys()

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