7

I am trying to retrieve the auto increment value of last inserted data in mySQL. Here is my code:

public int getAutoIncrementProductID() {
    ResultSet rs = null;
    DBController db = new DBController();
    db.getConnection();
    int autoIncKeyFromFunc = -1;
    rs = db.readRequest("SELECT LAST_INSERT_ID()");
    try {
        if (rs.next()) {
            autoIncKeyFromFunc = rs.getInt(1);
            System.out.println("AUTO ID IS " + autoIncKeyFromFunc);
            rs.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    db.terminate();
    return autoIncKeyFromFunc;
}

However, these codes keep returning me 0 value although the auto increment column in database is keep increasing. It just wont get the auto increment value of last inserted data. Anybody could help?

1

6 Answers 6

12

You should use LAST_INSERT_ID() after you insert something.

For LAST_INSERT_ID(), the most recently generated ID is maintained in the server on a per-connection basis. It is not changed by another client. It is not even changed if you update another AUTO_INCREMENT column with a nonmagic value (that is, a value that is not NULL and not 0).

Source

You may also try

SELECT max(id) FROM tableName

But it will not suppose deleted rows.

2
  • @RiaD it told me column name not found
    – user2531590
    Commented Jul 13, 2013 at 6:37
  • @Gwen instead of id use the actual column name of your auto increment column in the table. Commented Jul 13, 2013 at 14:38
3

How about this?

SELECT your_id FROM your_table ORDER BY your_id DESC LIMIT 1
3
  • I want to use this solution for my case because i want to fetch row data directly. However, i have a question : is it fast compared to select max(id) and then fetch data by id? For example, if i have 1 000 000 rows, it doesn't impact performance? Thank you. Commented Feb 18, 2023 at 6:47
  • @RAZAFINARIVOHanania apparently using aggregate function in a large data is the fastest way. However, if the case is you need to still fetch the rows then ORDER BY and LIMIT is still preferable Commented Mar 28, 2023 at 10:05
  • How this will work on the table with 1 000 000 000 rows?
    – mochalygin
    Commented Sep 8, 2023 at 13:53
1

I think since you are using Jdbc there is another way to get generated key is to use API connection. createStatement (Statement.RETURN_GENERATED_KEYS); Look at this thread PreparedStatement with Statement.RETURN_GENERATED_KEYS

1

How about this?

SHOW TABLE STATUS FROM Database_Name LIKE 'TableName' ;

0

I use this:

SELECT auto_increment + 1 AS NEXT_ID
FROM   `information_schema`.`tables`
WHERE  table_name = "table_name"
       AND table_schema = "database_name"
0

Be Careful when using mysql_insert_id() specially if you have multiple connections to the Database. Because It doesn't get the value of the query you've inserted. it gets the latest id of the table. It may be a row another query has inserted. Only use this function if you access Database in one connection.

If you want to get the id of the query you've inserted, try to select the row with an unique value you've inserted with that query. Ex : finding the user id of a user with his email address.

SELECT id from users where emailaddress='[email protected]' LIMIT 1

More details here : https://www.php.net/manual/en/function.mysql-insert-id.php

1
  • the function LAST_INSERT_ID() returns the id of the last insert regardless of the table but in the user session. A connection implies a user session so no problem
    – Alan Allen
    Commented Feb 15 at 9:27