更新mysql驱动5.1-47 Generated keys not requested. You need to specify Statement.RETURN_GENERATED_KEY

时间:2021-06-16 05:56:14

今天在更新mysql驱动后运行程序突然报如下错误:

java.sql.SQLException: Generated keys not requested. You need to specify Statement.RETURN_GENERATED_KEYS to Statement.executeUpdate(), Statement.executeLargeUpdate() or Connection.prepareStatement().
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:965)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:898)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:887)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:861)
at com.mysql.jdbc.StatementImpl.getGeneratedKeys(StatementImpl.java:1693)
at liubin.demo.Test.main(Test.java:23)

经过检查发现从5.1.7版本之后的mysql-connector增加了返回GeneratedKeys的条件,如果需要返回GeneratedKeys,则PreparedStatement需要显示添加一个参数Statement.RETURN_GENERATED_KEYS。说实话,更新程序不向下兼容是不是有点不厚道啊!!!

解决方法:

st = conn.prepareStatement(sql);

修改为:st = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);

更新mysql驱动5.1-47 Generated keys not requested. You need to specify   Statement.RETURN_GENERATED_KEY