Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Getting the ID of an INSERT in mysql

Options
  • 24-01-2007 1:01pm
    #1
    Registered Users Posts: 378 ✭✭


    I'm using a JDBC connector to talk to "MySQL 4.1.14"

    At the moment to return the ID I am performing an Insert followed by

    SELECT MAX(ID) FROM TABLE;

    This works fine for now but it is not future proof... obviously if a transaction happens before I call the MAX(ID) then this will not return the ID for the original Insert.

    SELECT LAST_INSERT_ID(); only returns 0 for me... but it would have the same result as above, with increased traffic errors will occur.

    So basically, does anyone know how to return the value of the autoincrement column of the record you are inserting?


Comments

  • Registered Users Posts: 6,509 ✭✭✭daymobrew




  • Registered Users Posts: 4,188 ✭✭✭pH


    If the table has a column with AUTO_INCREMENT then and stmt is a prepared statement which is an insert for that table then:
        public int performInsert(PreparedStatement stmt) {
            
            try{
                stmt.executeUpdate();
    
                 ResultSet rs = stmt.getGeneratedKeys();
                 if (rs.next()) {
                     return rs.getInt(1);
                 } else
                     throw new RuntimeException("MYSQL : No generated keys.");
            } catch (SQLException ex){
                throw new RuntimeException("SQLINSERT[" + stmt.toString() + "]",ex);
            }
        }
    


  • Registered Users Posts: 32,136 ✭✭✭✭is_that_so


    You might find the code below useful as well.
    function insertRec($db_query)
    {
    mysql_query("LOCK TABLES table_name WRITE;");
    mysql_query($db_query); //table insert here
    $ID=mysql_insert_id();
    mysql_query("UNLOCK TABLES");
    return $ID;
    }
    


  • Registered Users Posts: 3,886 ✭✭✭cgarvey


    sicruise wrote:
    So basically, does anyone know how to return the value of the autoincrement column of the record you are inserting?
    INSERT INTO user( id, name ) VALUES( NULL, 'user1' );
    SELECT MAX( last_insert_id() ) FROM user;
    

    last_insert_id() is connection/session-safe.


  • Registered Users Posts: 378 ✭✭sicruise


    Thanks a million for that PH ... I never noticed that method before...

    Works a treat!

    Thanks everyone else too... was racking my brain for a good while on this


  • Advertisement
Advertisement