检索刚插入到Java DB(Derby)数据库中的记录的ID [英] Retrieve id of record just inserted into a Java DB (Derby) database

查看:180
本文介绍了检索刚插入到Java DB(Derby)数据库中的记录的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆