Getting the last inserted ID from table mySQL and java

Would like to get the last inserted ID from mySQL table and display it on a text box. The following is my code:
// RETRIEVING GENERATED WO_NUMBER FROM A NEW DATA RECORD (AUTO_INCREMENT)
public int get_woID() throws Exception{
 __int woID=0;
      try{
          Statement stmt = con.createStatement();
          //ResultSet result = stmt.executeQuery("SELECT LAST_INSERT_ID(id) from table1");
____stmt.executeQuery("");
____ResultSet newid = stmt.getGeneratedKeys();
____newid.next();
____woID = newid.getInt(1);
__     }//try
     catch(SQLException sqle){
       System.out.println("Error Executing SQL");
       throw(sqle);
     }//catch
   return woID;
}

please help me get the correct values
mphagobAsked:
Who is Participating?
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
the query to run is very short:

SELECT LAST_INSERT_ID()
0
 
avinthmCommented:

> Statement stmt = con.createStatement();
>           //ResultSet result = stmt.executeQuery("SELECT LAST_INSERT_ID(id)
> from table1");

 Statement stmt = con.createStatement();
 ResultSet result = stmt.executeQuery("SELECT max(id) from table1");
 int lastInsertedId = result.getInt("id");

0
 
int_20hCommented:
Also, for compatibility to others DBs, you can use:

SELECT @@IDENTITY

I know it works on mySql 5.0, so, hope if works for your version.  This variable is a synonym for the LAST_INSERT_ID variable.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.