今天批量更新的时候报错了报ORA-01000: 超出打开游标的最大数,上网搜了一下,是因为批量更新导致的,当时再循环里执行prepareStatement,没有及时关闭,导致报错,然后可以用addBatch进行优化
一般来说,我们在写Java代码的时候,createStatement和prepareStatement都应该要放在循环外面,而且使用了这些Statment后,及时关闭。最好是在执行了一次executeQuery、executeUpdate等之后,如果不需要使用结果集(ResultSet)的数据,就马上将Statment关闭。
如果使用批处理和事物还是很慢,就需要将表添加一个索引,速度会提升起来,
以表中的唯一主键建索引
public static void updateProdStoage() {
// TODO Auto-generated method stub
try {
con = DBConn.getConnection();
String sql = "select * from O8980_prodStorage_201907 where prodstoragetip is not null";
String sql1 = "update O8980_prodStorage_201907 set prodstoragetip =? where item_id =? and prodstoragetip is not null";
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
String prodStorage = rs.getString("prodstoragetip");
String[] array = prodStorage.split(" ");
int total = 0;
for (int i = 0; i < array.length; i++) {
total = Integer.parseInt(array[i]) + total;
}
ps = con.prepareStatement(sql1);
//优化插入第一步 设置手动提交
con.setAutoCommit(false);
ps.setString(1, String.valueOf(total));
ps.setString(2, rs.getString("item_id"));
ps.addBatch();//优化插入
System.out.println(rs.getString("item_id") + "----" + total);
}
ps.executeBatch();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (con != null) {
con.close();
}
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}