[英]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.