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

时间:2017-01-18 17:13:22

标签: java jdbc db2

我想使用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。任何想法,为什么?

2 个答案:

答案 0 :(得分:0)

我设法找到了db2特定的解决方案。如果Sub CreateSheetsFromAList() Application.ScreenUpdating = False Sheets("Master").Select Sheets("Stock Removal").Visible = True Dim MyCell As Range, MyRange As Range Set MyRange = Sheets("Master").Range("A14") Set MyRange = Range(MyRange, MyRange.End(xlDown)) For Each MyCell In MyRange Sheets("Stock Removal").Copy after:=Sheets(Sheets.Count) 'creates a new worksheet Sheets(Sheets.Count).Name = MyCell.Value ' renames the new worksheet Next MyCell Sheets("Stock Removal").Select ActiveWindow.SelectedSheets.Visible = False Application.ScreenUpdating = True End Sub 对象返回自动生成的键,请调用PreparedStatement以检索包含自动生成的键的DB2PreparedStatement.getDBGeneratedKeys个对象数组。

ResultSet

//这里有更多代码

import com.ibm.db2.jcc.DB2PreparedStatement;

答案 1 :(得分:0)

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