MySQL版本问题引起的异常解决

从git上把代码拉到本地,代码执行添加操作报错Generated keys not requested. You need to specify Statement.RETURN_GENERATED

原代码:

public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement(sql);
                int index = 1;
                for (Object param : params) {
                    ps.setObject(index++, param);
                }
                return ps;
            }

解决办法:prepareStatement方法需要显示添加一个参数Statement.RETURN_GENERATED_KEYS。

修改后的代码:

 public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);//显式添加参数Statement.RETURN_GENERATED_KEYS
                int index = 1;
                for (Object param : params) {
                    ps.setObject(index++, param);
                }
                return ps;
            }

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

你可能感兴趣的:(IT相关)