如何使用preparestatement获取最后插入的行的ID? [英] How to get the id of last inserted row using preparedstatement?

查看:73
本文介绍了如何使用preparestatement获取最后插入的行的ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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)

When I use the following code also it gives error although I choose 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.");
        }

推荐答案

ps.executeUpdate(ps.RETURN_GENERATED_KEYS)

您发明了那个.它不存在.

You invented that. It doesn't exist.

ps = con.prepareStatement(Insert_Credential);

这也不告诉PreparedStatement返回生成的密钥.您需要这个:

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

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

这篇关于如何使用preparestatement获取最后插入的行的ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆