postgresql 如何使用preparedstatement获取最后插入行的id?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14845354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 00:47:45  来源:igfitidea点击:

How to get the id of last inserted row using preparedstatement?

javamysqldatabasepostgresqljdbc

提问by Daniel Morgan

I am using the following code to insert a new row to database, I need to get the id of the last inserted row but when I run the code it shows the following message:

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

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

When I use the following code also it gives error although I choose executeUpdate(String sql)

当我使用以下代码时,尽管我选择了 executeUpdate(String sql) 它也会出错

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

the table is as following:

下表如下:

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

my code

我的代码

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.");
        }

回答by user207421

ps.executeUpdate(ps.RETURN_GENERATED_KEYS)

You invented that. It doesn't exist.

你发明了那个。它不存在。

ps = con.prepareStatement(Insert_Credential);

That doesn't tell the PreparedStatementto return generated keys either. You need this:

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

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