数据库插入大量数据性能测试——批处理+事务VS普通插入

42 篇文章 1 订阅
25 篇文章 0 订阅

测试:sql server插入10000行数据


关键代码(批处理+事务):

public void insertUser() {
		String sql = "insert into users values(?,?)";
		Connection conn = getConnection();
		PreparedStatement ps = null;
		try {
			// 禁止自动提交事务
			conn.setAutoCommit(false);
			// 创建能返回自动生成的主键的值的预编译对象
			ps = conn.prepareStatement(sql);
			//开始时间的毫秒数
			Long start=System.currentTimeMillis();
			for (int i = 0; i < 10000; i++) {
				ps.setString(1, i+"");
				ps.setInt(2, 22);
				ps.addBatch();// 添加到批处理命令中
			}
			ps.executeBatch();// 执行批处理
			conn.commit();// 提交事务
			//结束时间的毫秒数
			Long stop=System.currentTimeMillis();
			//得到总耗时
			Long ms=stop-start; 
			System.out.println("插入一万记录耗时:"+ms+"毫秒");
		} catch (SQLException e) {
			e.printStackTrace();
			//取消事务
			try{
				conn.rollback();
			}catch(SQLException ee){
				ee.printStackTrace();
			}
		} finally {
			//打开自动提交事务
			try {
				conn.setAutoCommit(true);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			close(null, ps, conn);
		}
	}
结果:


关键代码(普通插入):

public void insertUser() {
		String sql = "insert into users values(?,?)";
		Connection conn = getConnection();
		PreparedStatement ps = null;
		try {
			// 创建能返回自动生成的主键的值的预编译对象
			ps = conn.prepareStatement(sql);
			//开始时间的毫秒数
			Long start=System.currentTimeMillis();
			for (int i = 0; i < 10000; i++) {
				ps.setString(1, i+"");
				ps.setInt(2, 22);
				ps.executeUpdate();
			}
			//结束时间的毫秒数
			Long stop=System.currentTimeMillis();
			//得到总耗时
			Long ms=stop-start; 
			System.out.println("插入一万记录耗时:"+ms+"毫秒");
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			close(null, ps, conn);
		}
	}
结果:


最后:差距还是挺大的!现在见识批处理和事务的高效了吧!


  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值