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

How do I get the AUTOINCREMENT value?

 
Kaydell Leavitt
Ranch Hand
Posts: 690
Eclipse IDE Firefox Browser Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 21321
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 690
Eclipse IDE Firefox Browser Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Paul,

The simplifies things quite a bit for me.

Kaydell
[ June 07, 2007: Message edited by: Kaydell Leavitt ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic