我试图检索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值.它只是不会得到最后插入数据的自动增量值.有人可以帮忙吗?
解决方法:
插入内容后应使用LAST_INSERT_ID().
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).
你也可以试试
SELECT max(id) FROM tableName
但它不会假设已删除的行.
标签:mysql
来源: https://codeday.me/bug/20190716/1478678.html