How to obtain the primary key of the Oracle database record after the JDBC Insert statement is executed

Source: Internet
Author: User

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 ));

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.