Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

last_insert_id()

 
Andreas Bystrom
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 231
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic