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);
	}

猜你喜欢

转载自blog.csdn.net/m0_38068812/article/details/81176568