File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes JDBC 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
Bookmark "last_insert_id()" Watch "last_insert_id()" New topic
Author

last_insert_id()

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:

HTH
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
Greenhorn

Joined: Apr 08, 2008
Posts: 25
I was just looking into the exact same issue.
Here's the preferred solution: http://dev.mysql.com/doc/refman/4.1/en/connector-j-usagenotes-basic.html#connector-j-examples-autoincrement-getgeneratedkeys

In short:
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: last_insert_id()