gpt4 book ai didi

java - 如何从 Oracle 中的 JDBC 批量插入中获取生成的键?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:57:10 26 4
gpt4 key购买 nike

我正在使用 JDBC 批量插入插入许多记录。有没有办法获取每条记录的生成 key ?我可以将 ps.getGeneratedKeys() 用于批量插入吗?

我正在使用 oracle.jdbc.OracleDriver

final String insert = "Insert into Student(RollNumber, Name, Age) values(StudentSEQ.nextval, ? , ?)";
final int BATCH_SIZE = 998;
int count = 0;
Connection con = null;
PreparedStatement ps = null;
try {
con = getConnection();
ps = con.prepareStatement(insert);
for (Student s : students) {
ps.setString(1, s.getName());
ps.setInt(2, s.getAge());
ps.addBatch();
count++;
if (count % BATCH_SIZE == 0) {
// Insert records in batches
ps.executeBatch();
}
}
// Insert remaining records
ps.executeBatch();
} finally {
if(ps != null)
ps.close();
release(con);
}

我正在考虑在循环内使用 ps.executeUpdate()ps.getGeneratedKeys() 以获得所需的结果。还有其他解决方案吗?

最佳答案

JDBC 4.1 specification ,第 13.6 节 检索自动生成的值 说:

It is implementation-defined as to whether getGeneratedKeys will return generated values after invoking the executeBatch method.

因此您需要检查您的驱动程序是否真的支持批量更新。如 the answer by Philip O. 所示,批量更新不支持检索生成的 key ,如 Oracle 12 JDBC Standards Support 中所述:

You cannot combine auto-generated keys with batch update.

在任何情况下,如果您的驱动程序支持它,那么您的 prepare 语句应该更改为以下代码以指示驱动程序检索生成的 key :

ps = con.prepareStatement(insert, Statement.RETURN_GENERATED_KEYS);

注意:您可能需要使用其他生成的键准备方法之一(prepareStatement(sql, columnIndexes)prepareStatement(sql, columnNames)),因为 Oracle 将使用我示例中的方法返回 ROW_ID

关于java - 如何从 Oracle 中的 JDBC 批量插入中获取生成的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15684297/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com