mysql 批量操作性能比较

  • 一.在操作数据库的时候,使用预编译(PreparedStatement)将会大大的提高操作数据库的性能优势如下:

        1). 代码的可读性和可维护性. (使用占位符表示参数?)

        2).能最大可能提高性能(预编译),MySQL不支持PreparedStatement的性能优化.

        3).能保证安全性.

  • 二.预编译高效体现(sql发送的数据库服务器)

        安全性分析-->语法分析-->语法编译-->选择执行-->返回结果集(结果)

        预编译池:先判断发送到DBMS的sql语句是否存在预编译池中,如果存在,则进行选择执行步骤,如果不存在,则按照上面过程执行一遍,并且把sql存放在预编译池中(注:Oracle支持预编译,mysql不支持)

三.mysql示例

  

// 没有使用批处理完成
	//InnoDB:15369ms
	//MyISAM:8464ms
	@Test
	public void testSaveByStatement() throws Exception {
		
		Connection conn = JdbcUtil.getConnection();
		Statement st = conn.createStatement();
		long begin = System.currentTimeMillis();
		for (int j = 1; j < 5000; j++) {
			String sql = "insert into t_student (name,age) values('tom',"+ j+")";
			st.executeUpdate(sql);
		}
		long end = System.currentTimeMillis();
		System.out.println(end - begin);
		JdbcUtil.realse(null, st, conn);
	}
	
	// 使用批处理完成
	//InnoDB:14641ms
	//MyISAM:7464ms
	@Test
	public void testBatchSaveByStatement() throws Exception {
		
		Connection conn = JdbcUtil.getConnection();
		Statement st = conn.createStatement();
		long begin = System.currentTimeMillis();
		for (int j = 1; j < 5000; j++) {
			String sql = "insert into t_student(name,age) values('tom',"+ j+")";
			st.addBatch(sql);  // 添加到批处理中
			if(j % 200 == 0){
				st.executeBatch(); // 执行
				st.clearBatch();  // 清除批处理
			}
		}
		long end = System.currentTimeMillis();
		System.out.println(end - begin);
		JdbcUtil.realse(null, st, conn);
	}
	
	// 没有使用批处理完成
	//InnoDB:13630
	//MyISAM:12323
	@Test
	public void testSaveByPrepareStatement() throws Exception {
		String sql = "insert into t_student(name,age) values('tom',?)";
		Connection conn = JdbcUtil.getConnection();
		PreparedStatement ps =  conn.prepareStatement(sql);
		long begin = System.currentTimeMillis();
		for (int j = 1; j < 5000; j++) {
			ps.setInt(1, j);
			ps.executeUpdate();
			ps.clearParameters();
		}
		long end = System.currentTimeMillis();
		System.out.println(end - begin);
		JdbcUtil.realse(null, ps, conn);
	}
	
	// 使用批处理完成
	//InnoDB:11118
	//MyISAM:4546
	@Test
	public void testBatchSaveByByPrepareStatement() throws Exception {

		String sql = "insert into t_student(name,age) values('tom',?)";
		Connection conn = JdbcUtil.getConnection();
		PreparedStatement ps =  conn.prepareStatement(sql);
		long begin = System.currentTimeMillis();
		for (int j = 1; j < 5000; j++) {
			ps.setInt(1, j);
			ps.addBatch();
			if(j % 200 == 0){
				ps.executeBatch();
				ps.clearBatch();
			}
		}
		long end = System.currentTimeMillis();
		System.out.println(end - begin);
		JdbcUtil.realse(null, ps, conn);
	}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值