How to get the auto incremented PK from Oracle database? [duplicate]
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.
精彩评论