批量更新优化addBatch()

今天批量更新的时候报错了报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();
			}
		}
	}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值