问题描述
我正在使用 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.
我看到这是一个常见问题,但我看到 解决方案 使用例如 MS SQL Server,Java DB 的等价物是什么?
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() 是为了.
当 准备您的语句 您传递自动生成的列的名称,然后您可以使用 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!