Java JDBC Get id after insert

I use triggers to set PK column values ​​for all tables, so I don't do any identifier operations in java, but I need an identifier after insertion.

How can I get the id?

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

Edit: Hi, I read the question again, now I have an exception such as "unsupported operation" (I translated the exact English form from my native language may vary). I assume this is oracle support for GetGeneratedKeys? Do you know anything about this?

Solution: As mentioned in the book on callablestatements, this statement can be used to execute stored procedures and functions. Unlike PreparedStatement, most databases do not prepare for a call because it is such a simple command. CallableStatement instances can be used to accurately return an object that will be stored in a stored procedure or function.

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;
+3
source share
1 answer

In this example, you can do this in PostgreSQL. Hope you can do something similar in Oracle.

INSERT INTO , serial. RETURN_GENERATED_KEYS prepareStatement().

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

, -:)

+5

Source: https://habr.com/ru/post/1758993/


All Articles