当前位置:首页 > 芯闻号 > 充电吧
[导读]测试:sql server插入10000行数据关键代码(批处理+事务):public void insertUser() { String sql = "insert into users val

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

结果:



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


本站声明: 本文章由作者或相关机构授权发布,目的在于传递更多信息,并不代表本站赞同其观点,本站亦不保证或承诺内容真实性等。需要转载请联系该专栏作者,如若文章内容侵犯您的权益,请及时联系本站删除( 邮箱:macysun@21ic.com )。
换一批
延伸阅读
关闭