开发者

How to get the auto incremented PK from Oracle database? [duplicate]

开发者 https://www.devze.com 2023-03-07 18:08 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: PLSQL JDBC: How to get last row ID?
This question already has answers here: Closed 11 years ago.

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.


You need to specify the possible generated keys that you want to retrieve.

PreparedStatement  pstmt = conn.prepareStatement(sql,new String [] {"ID_ORDER"});

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 :

DatabaseMetaData metaData =  conn.getMetaData();
log("SupportsGetGeneratedKeys?="+metaData.supportsGetGeneratedKeys());

More here : Retrieve the generated keys (JDBC Oracle)


Is customer.getID() a candidate key of the table? If so, you can run a SELECT after the INSERT to find the value of the generated PK. Alternatively, you can get rid of the trigger, get the next value of the SEQUENCE from the DB in Java, and use that as the PK for the INSERT. The drawback of this approach is that inserts from other applications will have to do the same too.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号