问题描述
我使用JDBC批量插入插入许多记录。
有没有办法为每条记录获取生成的密钥?
我可以使用 ps.getGeneratedKeys()
批量插入吗?
I am inserting many records using JDBC batch inserts.Is there any way to get the generated key for each record?Can I use ps.getGeneratedKeys()
with batch inserts?
我正在使用 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()
以获得所需的结果。任何其他解决方案?
I am thinking of using ps.executeUpdate()
along with ps.getGeneratedKeys()
inside the loop to get the desired result. Any other solutions?
推荐答案
根据以下页面,Oracle 12c似乎不支持将自动生成的密钥与批量更新相结合:
It appears that Oracle 12c does not support combining auto-generated keys with batch update according to the following page:
请参阅标记为限制的小节在检索自动生成的密钥部分
See the subsection labeled "Limitations" under the section "Retrieval of Auto-Generated Keys"
这篇关于如何从Oracle中的JDBC批量插入中获取生成的密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!