The answer to your IT questions
 

Advanced search  • Search tips
My QUESTIONS & ANSWERS
 Question:

How can I get PrimaryKey without select after insert?

User Asked by: ldunev
Published on: 15:10/04.12.2007
Status: OPEN
I try to get Primary Key value after insert through JDBC. I don't want to execute additional select statement.
 Answers: 1
Sort by: /\ date | rating
Image Answer by: lubod
Posted on: 15:10/04.12.2007
Rating: 2.4 from possible 5 with 10 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
  
| Home | Hall of fame | Register | Log in | Terms of service | Help | Contacts |