atr*_*thi 10 java oracle jdbc primary-key batch-insert
我使用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);
}
Run Code Online (Sandbox Code Playgroud)
我想使用的ps.executeUpdate()随ps.getGeneratedKeys()环内得到期望的结果.还有其他方法吗?
在JDBC 4.1规范,部分13.6 检索自动生成的值表示:
它是实现定义的,是否
getGeneratedKeys在调用executeBatch方法后返回生成的值.
因此,您需要检查您的驱动程序是否实际支持批量更新.正如Philip O.的回答所示,Oracle 12 JDBC标准支持中记录的批量更新不支持检索生成的密钥:
您无法将自动生成的密钥与批量更新组合在一起.
在任何情况下,如果您的驱动程序支持它,那么您的语句prepare应更改为以下代码,以指示驱动程序检索生成的密钥:
ps = con.prepareStatement(insert, Statement.RETURN_GENERATED_KEYS);
Run Code Online (Sandbox Code Playgroud)
注意:您可能需要使用其他生成的密钥之一准备方法(prepareStatement(sql, columnIndexes)或prepareStatement(sql, columnNames)),因为Oracle将ROW_ID使用我的示例中的方法返回.
根据以下页面,Oracle 12c 似乎不支持将自动生成的密钥与批量更新相结合:
http://docs.oracle.com/cd/E16655_01/java.121/e17657/jdbcvers.htm
请参阅“自动生成的密钥的检索”部分下标记为“限制”的小节
| 归档时间: |
|
| 查看次数: |
12213 次 |
| 最近记录: |