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

Getting primary keys

 
Alejandro Barrero
Ranch Hand
Posts: 339
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I create a row that has an integer primary key with auto-increment, so the database creates the primary key. But I need the key to use it as a foreign key in anothe table. How can I get the primary key?
 
Dave Salter
Ranch Hand
Posts: 293
Java Mac OS X Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The easiest way is to issue an SQL statement agains the database that gets the newly generated primary key. The SQL that you need to issue depends upon the datbase that you are using. For SQL Server, for example, you could issue a "select @@identity" SQL statement.

What database are you using?

Cheers,

Dave.
 
Alejandro Barrero
Ranch Hand
Posts: 339
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much. I am planning to use different databases so I will have to use the specific dialect, but knowing that something like that exists makes all the difference. I will execte the INSERT and SELECT SELECT @@IDENTITY AS NewID in the same statement to make it thread safe.
If you could tell me how to do it for other databases, that would save me a lot of time.
 
Dave Salter
Ranch Hand
Posts: 293
Java Mac OS X Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which database are you tagetting?

Dave.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic