Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

return autogenerated key

 
gaurav chaudhary
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have two tables....The autogenerated key of the first one which is also the primary key is the foreign key in the second one. Can u please tell me how do i get the id generated from the first table when I insert the record in it
thanks in advance
gaurav chaudharygaurav@yahoo.com
 
Irene Loos
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can have second query that reads immidiately after insert. Put in this query parameters that you used to generate the record. It should bring you back your id.
 
Jamie Robertson
Ranch Hand
Posts: 1879
MySQL Database Suse
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
some of the new drivers that implement the JDBC 3.0 interface have a Statement.getGeneratedKeys() method. Otherwise, you are looking at doing something like mentioned above or create your own autogenerated key using a millisecond date representation( long datatype ) as the key.
Jamie
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The preferred way would be JDBC 3.0 getGeneratedKeys(), but usually there is also database-specific syntax to get the last key generated in the current transaction; eg SELECT @@IDENTITY on SQL Server. You would execute this as you would any SQL query.
- Peter
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic