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

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

 

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。不过直接报错,不向下兼容也太不厚道了。

 

posted @ 2016-04-27 11:26  坚哥威武  阅读(8313)  评论(0编辑  收藏  举报