我正在使用以下代码向数据库插入新行,我需要获取最后插入行的 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.");
}