首页 > 数据库技术 > 详细

mysql获取自动生成的主键报错:Generated keys not requested. You need to specify Statement.RETURN_GENERATED_KEYS to Statement.execu

时间:2016-04-27 12:44:38      阅读:846      评论:0      收藏:0      [点我收藏+]

今天项目中需要获取刚插入的自动增长 的主键值:

 

pstmt=conn.prepareStatement(sql);
...
rs=pstmt.getGeneratedKeys();

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

上网查了之后才知道原来是5.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();

原因是:貌似从5.1.7版本之后的mysql-connector增加了返回GeneratedKeys的条件,如果需要返回GeneratedKeys,则PreparedStatement需要显示添加一个参数Statement.RETURN_GENERATED_KEYS。不过直接报错,不向下兼容也太不厚道了。

 

mysql获取自动生成的主键报错:Generated keys not requested. You need to specify Statement.RETURN_GENERATED_KEYS to Statement.execu

原文:http://www.cnblogs.com/gwq369/p/5438224.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!