5

我正在尝试检索 mySQL 中最后插入的数据的自动增量值。这是我的代码:

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;
}

但是,尽管数据库中的自动增量列不断增加,但这些代码一直返回 0 值。它只是不会获得最后插入数据的自动增量值。有人可以帮忙吗?

4

5 回答 5

9

你应该LAST_INSERT_ID()在插入东西后使用。

对于 LAST_INSERT_ID(),最近生成的 ID 在每个连接的基础上维护在服务器中。它不会被其他客户端更改。如果您使用非魔术值(即非 NULL 且非 0 的值)更新另一个 AUTO_INCREMENT 列,它甚至不会更改。

资源

你也可以试试

SELECT max(id) FROM tableName

但它不会假设已删除的行。

于 2013-07-13T05:05:37.947 回答
3

这个怎么样?

SELECT your_id FROM your_table ORDER BY your_id DESC LIMIT 1
于 2013-07-13T14:36:36.393 回答
1

我认为由于您使用的是 Jdbc,因此还有另一种获取生成密钥的方法是使用 APIconnection. createStatement (Statement.RETURN_GENERATED_KEYS);查看这个线程PreparedStatement with Statement.RETURN_GENERATED_KEYS

于 2013-07-13T14:32:44.093 回答
0

我用这个:

SELECT auto_increment + 1 AS NEXT_ID
FROM   `information_schema`.`tables`
WHERE  table_name = "table_name"
       AND table_schema = "database_name"
于 2019-03-09T10:05:30.560 回答
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='me@johndoe.com' LIMIT 1

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

于 2020-03-23T11:31:36.563 回答