如何从Oracle数据库中获取自动递增的PK? [英] How to get the auto incremented PK from Oracle database?
问题描述
可能重复:
PLSQL JDBC:如何获取最后一行ID?
我已经实现了一个触发器和一个自动递增PK的序列,我使用的是Oracle 10g作为数据库。
现在我想使用JAVA插入一些东西,但我需要在INSERT之后立即将增加的PK保存在变量中。我试过这个:
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();
但它不起作用。
推荐答案
您需要指定要检索的可能生成的密钥。
You need to specify the possible generated keys that you want to retrieve.
PreparedStatement pstmt = conn.prepareStatement(sql,new String [] {"ID_ORDER"});
请注意,列名称区分大小写。最后需要JDBC 3.0驱动程序和Oracle 10g R2或更高版本。
Note that the column name is case-sensitive. Finally a JDBC 3.0 driver and Oracle 10g R2 or better are required.
您可以通过检查DatabaseMetaData来检查当前安装是否支持此机制:
You can check if your current installation supports this mechanism by examining the DatabaseMetaData :
DatabaseMetaData metaData = conn.getMetaData();
log("SupportsGetGeneratedKeys?="+metaData.supportsGetGeneratedKeys());
更多信息:检索生成的密钥(JDBC Oracle)
这篇关于如何从Oracle数据库中获取自动递增的PK?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!