File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes JDBC and Relational Databases and the fly likes last_insert_id() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "last_insert_id()" Watch "last_insert_id()" New topic


Andreas Bystrom
Ranch Hand

Joined: Mar 05, 2003
Posts: 32
Hi all!
If I add a record that has a id field with auto_increment, how do I get the id created for this record?
I'm using mySQL and there is this method latest_insert_id() but I don�t get how I could invoke it using java.sql library. Has someone got a clue?
// Andreas
Juanjo Bazan
Ranch Hand

Joined: Feb 04, 2002
Posts: 231
The mySQL functions do not affect your java code.
You have to use the java.sql package as usual, just modify your sql statement:

Andreas Bystrom
Ranch Hand

Joined: Mar 05, 2003
Posts: 32
I actually wanted the id that was last inserted, and it was not to be used in a new sql statement. I finally found a way:

Then the long value of the id last inserted is in the variable insertId
// Andreas
Bojan Tomic

Joined: Apr 08, 2008
Posts: 25
I was just looking into the exact same issue.
Here's the preferred solution:

In short:
I agree. Here's the link:
subject: last_insert_id()
It's not a secret anymore!