位置:首页 » 文章/教程分享 » mysql获取自动生成的主键报错:Generated keys not requested.
今天项目中需要获取刚插入的自动增长 的主键值:
pstmt=conn.prepareStatement(sql);
...
rs=pstmt.getGeneratedKeys();

89897谁知道报错:Generated keys not requested. You need to specify Statement.RETURN_GENERATED_KEYS to Statement.execu

原来是MySQL5.1.5的包,替换成5.1.17之后,如下生成主键的代码都会报错:

Generated keys not requested. You need to specify Statement.RETURN_GENERATED_KEYS to Statement.executeUpdate() or Connection.prepareStatement().

将代码修改成这样就不会报错:

pstmt=conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);

rs=pstmt.getGeneratedKeys();

原因是:MySQL从5.1.7版本之后的mysql-connector增加了返回GeneratedKeys的条件,如果需要返回GeneratedKeys,则PreparedStatement需要显示添加一个参数Statement.RETURN_GENERATED_KEYS。