In applications, a table's primary key is often paid with an automatically increasing number, for example, the sequence of Oracle, and the expected primary key value after insertion. The following describes the related methods.
1. Use the returning Statement of Oracle.
PreparedStatement sta = conn. prepareStatement ("insert into logging values (TESTSEQ. NEXTVAL, SYSDATE) returning id? ");
Sta.exe cute ();
ResultSet rset = sta. getResultSet ();
While (rset. next ())
{
Int id = rset. getInt (1 );
}
If there are both input values and return values, you should:
PreparedStatementSta = conn. prepareStatement ("BEGININSERT INTO LOGGING VALUES
(TESTSEQ. NEXTVAL ,? ) Returning id ?;END;");
Sta = conn.PrepareCall(SqlText );
Sta. setString (1, srqID );
Sta. registerOutParameter (2, Types. NUMERIC );
Sta. execute ();
Return sta. getLong (2 );
Or use oracle's OraclePreparedStatement
String SQL = "insert into test values (1 ,?) Returning id? ";
OraclePreparedStatement pstt = (OraclePreparedStatement) conn. prepareStatement (SQL );
Pstt. setString (1, "xxx ");
Pstt. registerReturnParameter (2, OracleTypes. INTEGER );
Pstt.exe cuteUpdate ();
ResultSet rset = pstt. getReturnResultSet (); // rest is not null
While (rset. next ()){
Int id = rset. getInt (1 );
System. out. println ("Insert returnning:" + id );
}
2. Use getGeneratedKeys of JDBC to return the rowid of Oracle.
PreparedStatement sta = conn. prepareStatement ("insert into testtable values (TESTSEQ. NEXTVAL, 'aaa')", Statement. RETURN_GENERATED_KEYS );
Sta.exe cute ();
System. out. println (sta. getGeneratedKeys ());
ResultSet rest = sta. getGeneratedKeys ();
Rest. next ();
// Oracle rowid
System. out. println (rest. getString (1 ));