如何从Oracle数据库获取自增PK?
可能的重复:
PLSQL JDBC:如何获取最后一行 ID?
我有实现了一个触发器和一个用于自动递增 PK 的序列,我使用 Oracle 10g 作为数据库。 现在我想使用 JAVA 插入一些东西,但我需要在插入之后将增加的 PK 保存在变量中。我尝试过这个:
PreparedStatement pstmt = connection.prepareStatement("INSERT INTO sometable
VALUES(?, ?)",
Statement.RETURN_GENERATED_KEYS);
pstmt.setInt(1, 5);
pstmt.setString(2, "Username");
pstmt.executeUpdate();
ResultSet resultSet = pstmt.getGeneratedKeys();
但它不起作用。
Possible Duplicate:
PLSQL JDBC: How to get last row ID?
I have implemented a trigger and a sequence for auto incrementing PK, I'm using Oracle 10g as database.
Now I want to INSERT something using JAVA, but I need to save the incremented PK in a variable right after the INSERT. I tried this:
PreparedStatement pstmt = connection.prepareStatement("INSERT INTO sometable
VALUES(?, ?)",
Statement.RETURN_GENERATED_KEYS);
pstmt.setInt(1, 5);
pstmt.setString(2, "Username");
pstmt.executeUpdate();
ResultSet resultSet = pstmt.getGeneratedKeys();
But it doesn't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要指定要检索的可能生成的密钥。
请注意,列名称区分大小写。最后,需要 JDBC 3.0 驱动程序和 Oracle 10g R2 或更高版本。
您可以通过检查 DatabaseMetaData 来检查当前安装是否支持此机制:
You need to specify the possible generated keys that you want to retrieve.
Note that the column name is case-sensitive. Finally a JDBC 3.0 driver and Oracle 10g R2 or better are required.
You can check if your current installation supports this mechanism by examining the DatabaseMetaData :
customer.getID()
是表的候选键吗?如果是这样,您可以在INSERT
之后运行SELECT
来查找生成的 PK 的值。或者,您可以摆脱触发器,从 Java 数据库中获取SEQUENCE
的下一个值,并将其用作INSERT
的 PK。这种方法的缺点是来自其他应用程序的插入也必须执行相同的操作。Is
customer.getID()
a candidate key of the table? If so, you can run aSELECT
after theINSERT
to find the value of the generated PK. Alternatively, you can get rid of the trigger, get the next value of theSEQUENCE
from the DB in Java, and use that as the PK for theINSERT
. The drawback of this approach is that inserts from other applications will have to do the same too.