异常解决:Generated keys not requested. You need to specify Statement.RETURN_GENERA_KEYS to Statement.

  • Post author:
  • Post category:其他




异常解决:

Generated keys not requested. You need to specify Statement.RETURN_GENERATED_KEYS to Statement.execu


异常:jdbc无法获取自增主键

原因:jdbc驱动包( mysql-connector )版本的问题

我的是:5.1.37

修改前:

 public void add(Category bean) {
         String sql = "insert into category values( null , ? )";
        try(Connection con = JDBCUtils.getConnection(); PreparedStatement ps = con.prepareStatement(sql)){
            ps.setString(1,bean.getCname());

            ps.executeUpdate();
            ResultSet rs = ps.getGeneratedKeys();
            if (rs.next()) {
                int cid = rs.getInt(1);
                bean.setCid(cid);
            }

        }catch (SQLException e){
            e.printStackTrace();
        }
    }


修改后:

往prepareStatement()添加:

Statement.RETURN_GENERATED_KEYS

//第三行
PreparedStatement ps = con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS)



版权声明:本文为qq_42701294原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。