一尘不染

从MySQL数据库获取插入行的索引

sql

我正在使用Java(jdbc)与MySQL数据库进行交互。我的表的主索引是AUTO INCREMENT。当我插入一行时,我需要获取它刚收到的索引。我怎么做?


阅读 219

收藏
2021-05-16

共1个答案

一尘不染

来自:http :
//dev.mysql.com/doc/refman/5.0/en/connector-j-usagenotes-
basic.html#connector-j-usagenotes-last-insert-
id

stmt.executeUpdate(
        "INSERT INTO autoIncTutorial (dataField) "
        + "values ('Can I Get the Auto Increment Field?')",
        Statement.RETURN_GENERATED_KEYS);

//
// Example of using Statement.getGeneratedKeys()
// to retrieve the value of an auto-increment
// value
//

int autoIncKeyFromApi = -1;

rs = stmt.getGeneratedKeys();

if (rs.next()) {
    autoIncKeyFromApi = rs.getInt(1);
} else {

    // throw an exception from here
}

rs.close();

rs = null;
2021-05-16