简体   繁体   English

如何获取批量插入语句的自动生成键?

[英]How to get auto generated keys of batch insert statement?

I want to INSERT batch of records in a database (ie DB2) using JDBC batch statement and then obtain the auto generated IDs of inserted rows.我想使用 JDBC 批处理语句在数据库(即 DB2)中插入一批记录,然后获取插入行的自动生成的 ID。 How can I achieve using JDBC API?如何使用 JDBC API 实现?

Example Code:示例代码:

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();

The batch statement executes successfully, all rows inserted into database.批处理语句成功执行,所有行都插入到数据库中。 But when calling getGeneratedKeys() to retrieve generated keys, it returns an empty ResultSet .但是当调用getGeneratedKeys()来检索生成的密钥时,它返回一个空的ResultSet Any idea, why?任何想法,为什么?

I have managed to find the db2 specific solution.我设法找到了特定于 db2 的解决方案。 If the PreparedStatement object returns automatically generated keys, call DB2PreparedStatement.getDBGeneratedKeys to retrieve an array of ResultSet objects that contains the automatically generated keys.如果PreparedStatement对象返回自动生成的键,则调用DB2PreparedStatement.getDBGeneratedKeys来检索包含自动生成的键的ResultSet对象数组。

import com.ibm.db2.jcc.DB2PreparedStatement;

// more code here // 这里有更多代码

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);
    }
}
    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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用Java预准备语句Batch时如何获取表的自动生成键? - How to get auto generated keys of a table while using java prepared statement Batch? 如何从Oracle中的JDBC批量插入中获取生成的密钥? - How to get generated keys from JDBC batch insert in Oracle? BatchSqlUpdate - 如何获取自动生成的密钥 - BatchSqlUpdate - how to get auto generated keys Mybatis使用生成的键进行批量插入 - Mybatis Use generated keys for Batch Insert 如何获得自动生成的键并设置结果集类型? - How can I get auto generated keys and set the resultset type? MyBatis,如何获取插入的自动生成密钥? [MySQL的] - MyBatis, how to get the auto generated key of an insert? [MySql] PreparedStatement.RETURN_GENERATED_KEYS 不适用于批量插入 - PreparedStatement.RETURN_GENERATED_KEYS not working with batch insert 尝试批量插入具有自动生成的ID的对象时出现NonUniqueObjectException - NonUniqueObjectException when trying to batch insert Objects with Auto-Generated ID 使用jdbc模板批量更新插入或更新记录后如何获取自动生成的主键? - How to get auto generated primary key after inserting or updating record using jdbc template batch update? JDBC如何从具有多个值查询的单个插入中获取所有生成的键? - JDBC How to get all generated keys from single insert with many values query?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM