加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 插入行并获取生成的ID

发布时间:2020-12-15 00:04:50 所属栏目:Java 来源:网络整理
导读:我正在尝试使用 Spring的JdbcTemplate类将一行插入名为transaction的 MySQL表中并获取生成的ID.相关代码是: public Transaction insertTransaction(final Transaction tran) { // Will hold the ID of the row created by the insert KeyHolder keyHolder =
我正在尝试使用 Spring的JdbcTemplate类将一行插入名为transaction的 MySQL表中并获取生成的ID.相关代码是:
public Transaction insertTransaction(final Transaction tran) {

    // Will hold the ID of the row created by the insert
    KeyHolder keyHolder = new GeneratedKeyHolder();

    getJdbcTemplate().update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {

            PreparedStatement ps = connection.prepareStatement(INSERT_TRAN_SQL);
            ps.setString(1,tran.getTransactionType().toString());

            Date sqlDate = new Date(tran.getDate().getTime());
            ps.setDate(2,sqlDate);
            ps.setString(3,tran.getDescription());

            return ps;
        }
    },keyHolder);

    tran.setId(keyHolder.getKey().longValue());
    return tran;
}

但是调用getJdbcTemplate().update会抛出以下异常

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

我可以插入行并获取生成的ID,而不放弃JdbcTemplate吗?我使用的是Spring 2.5,MySQL 5.5.27和MySQL Connector 5.1.26.

解决方法

请准备好您的声明,如下所示
PreparedStatement ps = connection.prepareStatement(
                           INSERT_TRAN_SQL,Statement.RETURN_GENERATED_KEYS);

底层JDBC驱动程序(在这里间接通过Spring的JdbcTemplate使用)需要提示您要检索生成的密钥.这可以在准备PreparedStatement时完成

connection.prepareStatement(strSQL,Statement.RETURN_GENERATED_KEYS);

或者,在执行声明时

statement.executeUpdate(strSQL,Statement.RETURN_GENERATED_KEYS);

这也是java.sql.SQLException指向的内容.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读