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

拈花ヽ惹草 提交于 2021-02-07 09:38:55

问题


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().

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)

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

回答1:


ps.executeUpdate(ps.RETURN_GENERATED_KEYS)

You invented that. It doesn't exist.

ps = con.prepareStatement(Insert_Credential);

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

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


来源:https://stackoverflow.com/questions/14845354/how-to-get-the-id-of-last-inserted-row-using-preparedstatement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!