【问题标题】:How to get the id of last inserted row using preparedstatement? [duplicate]如何使用preparedstatement获取最后插入行的id? [复制]
【发布时间】:2023-03-29 11:33:01
【问题描述】:

我正在使用以下代码向数据库插入新行,我需要获取最后插入行的 id,但是当我运行代码时,它会显示以下消息:

SEVERE: java.sql.SQLException: Generated keys not requested. You need to specify   
Statement.RETURN_GENERATED_KEYS to Statement.executeUpdate() or 
Connection.prepareStatement().

当我使用以下代码时,虽然我选择了 executeUpdate(String sql),但它也会给出错误

  ps.executeUpdate(ps.RETURN_GENERATED_KEYS);
  error >> no suitable method found for executeUpdate(int)

表格如下:

       credential 
          int         ID   primary key, auto increment
          varchar(10) name 

我的代码

String Insert_Credential = "Insert into credential values("
                    + "?,?)";
            ps = con.prepareStatement(Insert_Credential);
            ps.setInt(1, 0);
            ps.setString(2, "username");
            ps.executeUpdate();
            ResultSet generatedKeys = ps.getGeneratedKeys();
        if (generatedKeys.next()) {
             System.out.println("id is"+generatedKeys.getLong(1));
             return generatedKeys.getInt(1);
        } else {
            throw new SQLException("Creating user failed, no generated key obtained.");
        }

【问题讨论】:

  • 确定不是mysql和postgressql?
  • @BrianWebster,不管数据库是什么吗?
  • 是的,这很重要:没有获取最后插入的 id 的 ANSI 标准方法
  • @Bohemian 但在 JDBC 中有。

标签: java mysql database postgresql jdbc


【解决方案1】:
ps.executeUpdate(ps.RETURN_GENERATED_KEYS)

你发明的。它不存在。

ps = con.prepareStatement(Insert_Credential);

这也不会告诉PreparedStatement 返回生成的密钥。你需要这个:

ps = con.prepareStatement(Insert_Credential, Statement.RETURN_GENERATED_KEYS);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-07
    • 2019-11-21
    • 2011-07-27
    • 1970-01-01
    • 2023-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多