• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How do I get the AUTOINCREMENT value?

 
Ranch Hand
Posts: 694
Mac OS X Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Marshal
Posts: 28177
95
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 694
Mac OS X Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Paul,

The simplifies things quite a bit for me.

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