MySQL: Auto_increment - return the next/current value?

Discussion in 'MySQL' started by Teelo, Feb 28, 2009.

  1. #1
    So I'm normally an avid Oracle user, where I would use a transaction involving a SEQUENCE to solve this problem, but at the moment I need to use MySQL for my current project.

    Say I've got a table setup like so:

    TABLE_NAME
    ---------------------
    Table_ID INT PRIMARY KEY AUTO_INCREMENT
    Field VARCHAR(10)

    Now, in my application code, say I have a method like so:

    public int addRow(String data) {
         db.query("INSERT INTO TABLE_NAME (Field) VALUES (" + data + ")");
         return ?????;
    }
    Code (markup):
    I need this method to return the ID/primary key of the newly added row, which is determined by the database by using AUTO_INCREMENT.

    Under Oracle, I could just make a transaction, lock the table, lock the sequence, insert the row, return the sequences current value...

    However, I am not sure of a way to do this under MySQL?
     
    Teelo, Feb 28, 2009 IP
  2. CarPriceDatabase

    CarPriceDatabase Guest

    Messages:
    39
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    after you insert your data, do another query

    select last_insert_id()

    then you will get it.
     
    CarPriceDatabase, Feb 28, 2009 IP
  3. Teelo

    Teelo Peon

    Messages:
    14
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Hmm, does MySQL keep that call safe if multiple transactions are running constantly?
     
    Teelo, Feb 28, 2009 IP
  4. mwasif

    mwasif Active Member

    Messages:
    816
    Likes Received:
    23
    Best Answers:
    1
    Trophy Points:
    70
    #4
    MySQL Manual is the best place to know about MySQL. It says
     
    mwasif, Mar 1, 2009 IP