mehmet6parmak
mehmet6parmak

Reputation: 4857

Java JDBC Retrieve ID After Insert

I use triggers to set PK column values of all tables so i do not do any operation about IDs in java but i need the ID after insert.

How can i get the ID?

stat.execute("INSERT INTO TPROJECT_PROCESS_GROUP(NPROJECT_ID,VDESCRIPTION) " +
                "VALUES(" +
                "'" + projectID + "'," +
                "'" + description + "'" +
                "");

Edit: Hi again I read the question, now I get an exception like 'unsupported operation'(i translated from my native language the exact english form might be different). i guess this is about oracle's support for GetGeneratedKeys? Do you know anything about this?

Solution: As mentioned in a book about callablestatements This statement can be used to execute stored procedures and functions. Unlike the PreparedStatement, most databases do not perform any preparation for the call,because it is such a simple command. The CallableStatement instances can be used toreturn the object that the stored procedure—or function, to be more exact—returned.

OracleConnection conn = null;
    //OraclePreparedStatement pstat = null;
    OracleCallableStatement cstat = null;
    String sql = "BEGIN INSERT INTO TPROJECT P (VPROJECT_TITLE,VPROJECT_DESC)    VALUES(?,?) RETURNING P.NPROJECT_ID INTO ?;  END;";
    try {
        conn = ConnectionUtility.GetConnection();
        cstat = (OracleCallableStatement)conn.prepareCall(sql);

        cstat.setString(1, title);
        cstat.setString(2, description);
        cstat.registerOutParameter(3, OracleTypes.NUMBER);
        cstat.execute();

        int returnedID = cstat.getInt(3);
//          System.out.println(returnedID);

        conn.close();

        return returnedID;

Upvotes: 4

Views: 17131

Answers (1)

Ben
Ben

Reputation: 3042

This example is how you would do it in PostgreSQL. Hopefully you can do something similar in Oracle.

This is how you get the id after INSERT INTO for auto-generated keys like serial . Important here is to provide RETURN_GENERATED_KEYS in the prepareStatement() call.

Resultset result;
PreparedStatement prep;
String query = "INSERT INTO myRel (data) VALUES (?)";

prep = db.prepareStatement(query ,Statement.RETURN_GENERATED_KEYS);

result = prep.getGeneratedKeys();

if(result.next() && result != null){
   System.out.println("Key: " + result.getInt(1));
} else {
   System.out.println("No, Nop nada");
}

Hope that helps someone :)

Upvotes: 7

Related Questions