in Advanced 

Question preview

HomeQuestion preview:
Log in

How can I get PrimaryKey without select after insert?

I try to get Primary Key value after insert through JDBC. I don't want to execute additional select statement.
Do you know someone who could answer? Ask him for help
Answers: 1
Sort by: date rating
image lubod
17:10/04.12.2007
2.5 from possible 5 with 11 votes
Put primary key column in insert columns, it must be of type SERIAL.
Put zero in insert values for PrimaryKey(PK) column.
Put constant on prepare statement method of JDBC connection
Get result from prepared statement after insert with getGeneratedKeys()
It returns a result set, get generated key from result set and close it.

Example :
...
protected final String SQL_INSERT = "INSERT into table (id) VALUES ( 0 )";
...
connection.prepareStatement(SQL_INSERT, Statement.RETURN_GENERATED_KEYS)
...
rSet = aStmt.getGeneratedKeys();            
    if (rSet.next()) {
       return new Long(rSet.getLong(1));
    }
     rSet.close();
Vote:
Please vote! Your opinion matters!
If you haven't found what you've looking for, post a question
Ask question
| Home | Hall of fame | Registration | Log in | Terms of service | Privacy policy | Help | Contacts | RSS |