wood burning stoves 2.0*
The moose likes JDBC and the fly likes Getting primary keys Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Databases » JDBC
Bookmark "Getting primary keys" Watch "Getting primary keys" New topic
Author

Getting primary keys

Alejandro Barrero
Ranch Hand

Joined: Aug 01, 2005
Posts: 319
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?


Your help will be greatly appreciated,
Alejandro Barrero
Dave Salter
Ranch Hand

Joined: Jul 20, 2005
Posts: 292

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

Joined: Aug 01, 2005
Posts: 319
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

Joined: Jul 20, 2005
Posts: 292

Which database are you tagetting?

Dave.
 
GeeCON Prague 2014
 
subject: Getting primary keys