File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes JDBC and Relational Databases and the fly likes DB2 and automated PK genearation.. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "DB2 and automated PK genearation.." Watch "DB2 and automated PK genearation.." New topic

DB2 and automated PK genearation..

Saniya Ansari
Ranch Hand

Joined: Sep 30, 2002
Posts: 48
I'm using DB2 for a project.. I want to be able to genearate an automated PK which can just be a serial number like 1, 2,3.....
So I want to know that how can i do that with DB2
Secondly, When i insert I want to know what was the PK that was genearted.. so how can i do that.. like i'll execute the insert statement for example with a persons details.. a record is inserted and a pk is generated.. so how do i get that pk value..


Jeanne Boyarsky
author & internet detective

Joined: May 26, 2003
Posts: 33124

You can use an identity column.

Candle has a short example. (search for "identity" in the list of features.)

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
Dana Hanna
Ranch Hand

Joined: Feb 28, 2003
Posts: 227
Note that this feature became available with DB2 version 7. DB2 5.2 and 6.1 have no method of automated key generation.
Saniya Ansari
Ranch Hand

Joined: Sep 30, 2002
Posts: 48
Thanks you guys.. one more part that i'm trying to figure out is that how do i get that key that was generated back.. bcoz usually in select we'll give the primary key and select a record.. i can i suppose make a query and put the rest of the fields for example name, address, phone, email to match with the record i just inserted and get its id but this sounds like a less efficient method.. are there any other ways someone can suggest...
the question is agand if i'm using an automated pk generated by db, after insert how do i get this pk back right after i have inserted the record...
I agree. Here's the link:
subject: DB2 and automated PK genearation..
It's not a secret anymore!