MySQL问题记录——getGeneratedKeys MySQL问题记录——getGeneratedKeys

摘要:本文主要记录了新增记录并获取自增主键时出现的原因及解决办法。

问题重现

在使用JdbcTemplate尝试新增一条记录并获取自增主键时,系统后台报错了。

代码:

 1 String sql = "insert into bs_book(title, author) values(?, ?)";
 2 KeyHolder keyHolder = new GeneratedKeyHolder();
 3 jdbcTemplate.update(new PreparedStatementCreator() {
 4     @Override
 5     public PreparedStatement createPreparedStatement(Connection con)
 6             throws SQLException {
 7         PreparedStatement prepareStatement = con.prepareStatement(sql);
 8         prepareStatement.setString(1, "平凡的世界");
 9         prepareStatement.setString(2, "路遥");
10         return prepareStatement;
11     }
12 }, keyHolder);
13 System.out.println("id=" + keyHolder.getKey().intValue());

MySQL的驱动为5.1.7版本的报错信息:

1 Caused by: java.sql.SQLException: !Statement.GeneratedKeysNotRequested!

MySQL的驱动为5.1.7以后的版本的报错信息:

1 Caused by: java.sql.SQLException: Generated keys not requested. You need to specify Statement.RETURN_GENERATED_KEYS to Statement.executeUpdate() or Connection.prepareStatement().

解决办法

在使用Connection获取PreparedStatement的时候,同时传入一个常量参数:

1 PreparedStatement prepareStatement = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

问题说明

MySQL的驱动版本在5.1.7之前是不会报这个异常的,在5.1.7及以后的版本中,如果要使用PreparedStatement对象的getGeneratedKeys()方法获取插入的主键,就必须要在使用Connection获取PreparedStatement的时候传入一个常量,否则就会报错。

在5.1.7版本中报错:

1 Caused by: java.sql.SQLException: !Statement.GeneratedKeysNotRequested!

在5.1.7以后的版本中报错:

1 Caused by: java.sql.SQLException: Generated keys not requested. You need to specify Statement.RETURN_GENERATED_KEYS to Statement.executeUpdate() or Connection.prepareStatement().