aspose file tools*
The moose likes JDBC and the fly likes How do I get the AUTOINCREMENT value? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC
Bookmark "How do I get the AUTOINCREMENT value?" Watch "How do I get the AUTOINCREMENT value?" New topic
Author

How do I get the AUTOINCREMENT value?

Kaydell Leavitt
Ranch Hand

Joined: Nov 18, 2006
Posts: 689

If I INSERT a record into a database a using JDBC / SQL INSERT statement, how do I get the value of the AUTOINCREMENT field that I just inserted?

In single-user, I can know that no other thread has inserted into the same database table and do something like the following, where ID is my AUTOINCREMENT field and Items is my database table.

SELECT ID FROM Items ORDER BY ID DESC LIMIT 1

But, will this sort of thing work for multi-user? If I'm in a transaction, will I see the last ID that my transaction has inserted and not the IDs that other transactions may have inserted?

Kaydell
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18902
    
    8

After you use a Statement (or PreparedStatement, which is a subclass) to do an INSERT, follow up by calling that Statement's getGeneratedKeys() methods. It returns a ResultSet containing the auto-generated keys, if any.

You might find that you have to do your INSERT like this:although some database drivers don't have to be reminded like that.
Kaydell Leavitt
Ranch Hand

Joined: Nov 18, 2006
Posts: 689

Thanks Paul,

The simplifies things quite a bit for me.

Kaydell
[ June 07, 2007: Message edited by: Kaydell Leavitt ]
 
 
subject: How do I get the AUTOINCREMENT value?