We help IT Professionals succeed at work.

Getting the last inserted ID from table mySQL and java

mphagob
mphagob asked
on
Medium Priority
4,946 Views
Last Modified: 2012-08-13
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
Comment
Watch Question

Billing Engineer
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2009
Commented:
the query to run is very short:

SELECT LAST_INSERT_ID()

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
Commented:

> 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");

Commented:
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.
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.