INSERT, and get the auto-incremented value

倾然丶 夕夏残阳落幕 提交于 2020-01-11 09:48:27

问题


Consider the following table:

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

To which I'd insert an entry this way.

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

How does one know what value for id was created? Just doing a SELECT using the name field is not valid, because there can be duplicate entries.


回答1:


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.




回答2:


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()




回答3:


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:



来源:https://stackoverflow.com/questions/6791645/insert-and-get-the-auto-incremented-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!