【问题标题】:How to get auto generated keys of batch insert statement?如何获取批量插入语句的自动生成键?
【发布时间】:2017-01-18 17:13:21
【问题描述】:

我想使用 JDBC 批处理语句在数据库(即 DB2)中插入一批记录,然后获取插入行的自动生成的 ID。如何使用 JDBC API 实现?

示例代码:

String SQL_INSERT = "INSERT INTO TABLE1 (CURRENT_TIMESTAMP) VALUES (?) ";

Connection connection = DriverManager.getConnection("jdbc:db2://localhost:900/DATABASE");
PreparedStatement statement = connection.prepareStatement(SQL_INSERT, Statement.RETURN_GENERATED_KEYS);

// first batch
statement.setTimestamp(1, getCurrentTimestamp());
statement.addBatch();

//  second batch
statement.setTimestamp(1, getCurrentTimestamp());
statement.addBatch();

int[] insertedRows = statement.executeBatch();

ResultSet generatedKeys = statement.getGeneratedKeys();

批处理语句成功执行,所有行都插入数据库。但是当调用getGeneratedKeys() 来检索生成的密钥时,它返回一个空的ResultSet。有什么想法,为什么?

【问题讨论】:

  • 批量执行时是否支持检索生成的密钥取决于实现。 JDBC 不需要支持。
  • 您是否尝试过使用int[]String[] 指定自动生成的列的变体?
  • @Stavr00 是的,我在PreparedStatement 中尝试了变体int[]String[] 进行批处理,ResultSetgetGeneratedKeys() 方法上为空。
  • 您可能必须使用FINAL TABLE 特殊对象来返回插入的元素
  • JDBC 驱动程序支持getGeneratedKeys() 方法,否则应该抛出SQLFeatureNotSupportedException 异常。

标签: java jdbc db2


【解决方案1】:

我已经设法找到了 db2 特定的解决方案。如果PreparedStatement 对象返回自动生成的键,则调用DB2PreparedStatement.getDBGeneratedKeys 以检索包含自动生成的键的ResultSet 对象数组。

import com.ibm.db2.jcc.DB2PreparedStatement;

//这里有更多代码

ResultSet[] result = ((DB2PreparedStatement) preparedStatement).getDBGeneratedKeys();

for (int i = 0; i < result.length; i++) {
    while (result[i].next()) {
        ResultSet rs = result[i];
        java.math.BigDecimal generatedKey = rs.getBigDecimal(1);
        System.out.println("Automatically generated key value = " + generatedKey);
    }
}

【讨论】:

  • 谢谢。还是应该说,DB2 JDBC 驱动程序的开发者应该羞愧地低下头!!!
【解决方案2】:
    objPsmt.executeBatch();
    try (ResultSet rs = objPsmt.getGeneratedKeys()) {
        if (rs != null) {
            while (rs.next()) {
                int generatedId = rs.getInt(1);
                generatedIds.add(generatedId);
            }
        }
    } catch (Exception e) {
        LOGGER.error("Exception while generating ids ", e);
    }

【讨论】:

  • 你能解释一下你做了什么吗?
猜你喜欢
  • 2013-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-07
  • 2011-04-03
  • 2013-10-26
相关资源
最近更新 更多