• 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
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Devaka Cooray
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
Bartenders:
  • Carey Brown
  • Roland Mueller

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: 28295
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 ]
 
incandescent light gives off an efficient form of heat. You must be THIS smart to ride this ride. Tiny ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic