Retrieve Automatically Generated Keys in JDBC

Two steps to implement:
1 Step : 
Convey your intentions that you want to retrieve Generated Keys with help of following syntax

 PreparedStatement pst = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS) ;

One thing to note that for some JDBC Drivers such as DB2, Oracle, above mentioned syntax may not work.

In those cases following syntax may help you
 PreparedStatement psmt = con.prepareStatement(sql, new String[]{"USER_ID"})

In String Array passed as an argument, you specify column names you want to retrieve or u can also specify indexes.

2 Step : Fetch Generated Keys

Fetch generated keys in a ResultSet as following

 rs = psmt.getGeneratedKeys();

Following is example code for this


 import java.sql.*;
import com.ibm.db2.jcc.*;

Connection con;
Statement stmt;
ResultSet rs;

stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO EMP_PHONE
(EMPNO, PHONENO) VALUES ('123', '555')",
Statement.RETURN_GENERATED_KEYS);
rs = stmt.getGeneratedKeys();
if (rs.next())
{ System.out.println("Automatically generated key value = " + rs.getString(1)); }
rs.close();
stmt.close();
by the way i have noticed that we can retrieve any column from last inserted row, for this i used the method mentioned for DB2, Oracle above.

0 nhận xét:

Đăng nhận xét