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 Trouble using LAST_INSERT_ID() to retrieve the last inserted record ID Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC
Bookmark "Trouble using LAST_INSERT_ID() to retrieve the last inserted record ID" Watch "Trouble using LAST_INSERT_ID() to retrieve the last inserted record ID" New topic
Author

Trouble using LAST_INSERT_ID() to retrieve the last inserted record ID

Brian K Swingle
Ranch Hand

Joined: Jun 20, 2003
Posts: 39
Hello all,
I'm using the code below to write data about a particular user to a database table then i want to retrieve the Unique Key for purposes of passing the number on to via email so that support personel may retirieve the users data at a later time. I'm using MySQL and a JDBC connection obvously. The issue i'm having is not that i'm recieveing an error. But the LAST_INSERT_ID() only returns '0' . and the RecordNumber field which is the Unique Key field and is set to Auto Increment is up to like 12,000 rows. Do you have any idea why it would return '0' Am i using this correctly? Any help would be greatly appreciated.
Thanks
Brian
conn2 = DriverManager.getConnection("jdbc:mysql://localhost/Database?user=User&password=Password");
stmt2 = conn2.createStatement();
String dbquery = "INSERT INTO Dump ( ) VALUES ( )";
rs3 = stmt.executeQuery(dbquery);
System.out.println("@ Before Get Row ID@");
rs3 = stmt2.executeQuery("select LAST_INSERT_ID()");
System.out.println("@ Query Completed Get Row ID @");
if (rs3.next())
{
NewRecNum = rs3.getInt(1);
System.out.println("@NewRecNum: '"+NewRecNum+"' @");
}
System.out.println("@ After Get Row ID @");
Mathias Nilsson
Ranch Hand

Joined: Oct 13, 2003
Posts: 107
Just so you know!
Please read this before using LAST_INSERT_ID


SCJP2 , MCP( 70-229 ) , Preparing For SCWDC
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Trouble using LAST_INSERT_ID() to retrieve the last inserted record ID