【发布时间】:2013-03-19 00:52:03
【问题描述】:
我正在使用 JDBC 批量插入插入许多记录。
有什么方法可以获取每条记录的生成密钥吗?
我可以将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() 来获得所需的结果。还有其他解决方案吗?
【问题讨论】:
-
您在批量插入中使用序列吗?
-
是的,StudentSEQ 是表格的序列。
标签: java oracle jdbc primary-key batch-insert