日期:2014-05-16  浏览次数:20796 次

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

测试: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);
		}
	}
结果:


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


3楼lishehe昨天 15:33
厉害学习了
2楼aazz123qq前天 23:00
收藏了
1楼han_yankun2009前天 21:16
了解了