检索刚插入到Java DB(Derby)数据库中的记录的ID [英] Retrieve id of record just inserted into a Java DB (Derby) database
问题描述
我正在使用JDBC连接到Java DB数据库,并希望检索插入的最后一条记录的ID(自动递增).
I am connecting to a Java DB database with JDBC and want to retrieve the id (which is on auto increment) of the last record inserted.
I see this is a common question, but I see solutions using for example MS SQL Server, what is the equivalent for Java DB?
推荐答案
无需为此使用DBMS特定的SQL.
No need to use a DBMS specific SQL for that.
这就是 getGeneratedKeys ()是用于.
When preparing your statement you pass the name(s) of the auto-generated columns which you can then retrieve using getGeneratedKeys()
PreparedStatement pstmt = connection.prepareStatement(
"insert into some_table (col1, col2, ..) values (....)",
new String[] { "ID_COLUMN"} );
pstmt.executeUpdate();
ResultSet rs = pstmt.getGeneratedKeys(); // will return the ID in ID_COLUMN
请注意,在这种情况下,列名区分大小写(在Derby和许多其他DBMS中).
new String[] { "ID_COLUMN"}
与new String[] { "id_column"}
Note that column names are case sensitive in this case (in Derby and many other DBMS).
new String[] { "ID_COLUMN"}
is something different than new String[] { "id_column"}
或者,您也可以使用:
connection.prepareStatement("INSERT ...", PreparedStatement.RETURN_GENERATED_KEYS);
这篇关于检索刚插入到Java DB(Derby)数据库中的记录的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!