List:General Discussion« Previous MessageNext Message »
From:alec.cawley Date:November 9 2001 3:50pm
Subject:Re: Beginner question - getting last inserted ID
View as plain text  

> Anna Åhnberg writes:
>
> > Thanks, I actually already found the chapters but now I also now how to
> > use the function too!
>
> Let me quote from the manual:
> "LAST_INSERT_ID([expr])
>      Returns the last automatically generated value that was
>      inserted into an AUTO_INCREMENT column.
> mysql> select LAST_INSERT_ID();
>              -> 195"
>
> Thus you'd follow these steps:
> 1) INSERT into the table, and leave out the auto column or supply
>    a value of 0 or NULL
> 2) Verify that the query succeeded
> 3) SELECT LAST_INSERT_ID()
> 4) Get the result of the SELECT. On success, the SELECT will
>    return one row with one value in it. That is the number you're
>    interested in knowing.
>
> If you were using MySQL's C API there is a function that returns
> the ID without the need for steps 3-4, but since you are
> communicating over JDBC I don't think there's a simpler solution
> available. The query in step 3 is extremely fast, so it doesn't
> really matter, except that it's a bit more work to make an extra
> query.


You can access the fast mode from JDBC if you are using the mm.mysql driver:

  if (stmt instanceof org.gjt.mm.mysql.Statement) // Fast fetch of clipID when using MySQL
    return (int) ((org.gjt.mm.mysql.Statement) auxStmt).getLastInsertID () ;
  else // slower, but portable, way of getting clipID
    {
    ResultSet rs = stmt.executeQuery ("SELECT LAST_INSERT_ID ()") ;
    rs.next () ; //to first (only) row
    int res = rs.getInt (1) ;
    rs.close () ;
    return res ;
    }


Thread
Beginner question - getting last inserted IDAnna Ă…hnberg9 Nov
  • Re: Beginner question - getting last inserted IDCarl Troein9 Nov
    • Re: Beginner question - getting last inserted IDKodrik9 Nov
Re: Beginner question - getting last inserted IDCarl Troein9 Nov
  • Re: Beginner question - getting last inserted IDWilliam R. Mussatto9 Nov
RE: Beginner question - getting last inserted IDGregert Johnson9 Nov
Re: Beginner question - getting last inserted IDalec.cawley9 Nov