List:MySQL and Java« Previous MessageNext Message »
From:Cris Perdue Date:July 8 1999 5:16pm
Subject:Re: @@IDENTITY Support
View as plain text  
MySQL supports the syntax "select last_insert_id()", which returns the
last insert ID obtained through the MySQL Connection.  The JDBC drivers
for MySQL map a JDBC connection to a MySQL connection.

So if you don't use the same Connection from multiple threads
concurrently, a method like the following will do what you need.

  public static int getLastInsertID(Statement stmt) throws SQLException
{
    ResultSet rs = stmt.executeQuery("select last_insert_id()");
    try {
      if (!rs.next()) throw new SQLException("getLastInsertID: Empty
ResultSet");
      int value = rs.getInt(1);
      System.err.println("Last insert was "+value);
      return value;
    } finally {
      rs.close();
    }
  }

The MM and TWZ drivers each have a driver-specific method to do this,
but this way has the advantage that, while it is MySQL-specific, it is
driver-independent.

If you do inserts on the same Connection concurrently from different
threads (yes, it's legal), I'm not sure what you ought to do.  The
driver-specific primitives possibly might handle this situation.
--
Cris Perdue
Impact Online, Inc.
http://www.volunteermatch.org


Thread
@@IDENTITY SupportCarson Reynolds8 Jul
  • Re: @@IDENTITY SupportSasha Pachev8 Jul
  • Re: @@IDENTITY SupportCris Perdue8 Jul
    • Re: @@IDENTITY Support\"Terrence W. Zellers\"9 Jul
  • Re: @@IDENTITY SupportDavid Wall8 Jul
  • Re: @@IDENTITY SupportMark Matthews8 Jul