How to get the last insert ID from a table

后端 未结 4 907
臣服心动
臣服心动 2021-02-18 15:14

I want to get the value of the last ID insert in a table. How I can do this?

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-18 15:32

    int keyId = -1;
    preparedStatement.executeUpdate();
    resultSet = preparedStatement.getGeneratedKeys();
    if (resultSet.next()) {
        keyId = rs.getInt(1);
    }
    

    https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#getGeneratedKeys()

    Update: and don't forget to create preparedStatement with the following flag Statement.RETURN_GENERATED_KEYS otherwise it won't work)))

提交回复
热议问题