Ika's Weblog XML
Architecting the Thought.

After a very painful data-migration process

The blog has moved to a new location: www.freshblurbs.com

Please, kindly update your RSS Reader with the new URL:
http://www.freshblurbs.com/rss.xml

I apologize for the temporary inconvenience but in the long run the new server is going to be much more featue-rich and comfortable, benefiting both me and my kind readers.

10/09/06

JDBC: Get Last Insert's ID

OK, so I need this frequently enough to care (when I do direct JDBC for some data-mining, data-migration or any other mass-db operations) but not frequently enough to memorize (as I use Hibernate normally). Therefore, it seems like a good idea to post it here and be able to find it later, if I need it again :)

Oh, and maybe somebody else may benefit from it too. Heh

So, if, in JDBC, you need to get the IDs of the last inserts when using auto_generated primary keys on the database side (e.g. sequences) you should use getGeneratedKeys() method of java.sql.PreparedStatement

resultSet = pstmt.getGeneratedKeys(); 

if ( resultSet != null && resultSet.next() ) 
{ 
    newid = resultSet.getInt(1); 
}
The example shows how to get one ID but you can get all IDs of a mass-insert, as well. Pretty cool.

posted by irakli, 11:03 | link | comments


Copyright (C). Irakli Nadareishvili. Picktek Ltd.