JAVA JDBC连接SQL Server数据库进阶(二)---批处理

        在前面的学习中,每执行一条SQL语句就发送到数据库一次,PreparedStatement 虽然会将SQL语句存储再数据库端,但是他的参数也是分次的发送到数据库端,想象一下,如果我们有10000条数据或者更多,那就要和数据库交互10000次或更多,这会严重影响程序的性能。但如果可以一次性的将10000条数据发送到数据库端,而不是发送10000次,每次发送一条,这样程序性能会显著提升。

批处理的作用:

       一次和数据库交互过程中传输多条SQL语句或参数内容。

       减少和数据库交互次数,提升性能。

批处理的使用:

 Statement:

       addBatch();将当前SQL语句交给Statement(将所有要发送的SQL语句放到Statement维护的缓存中去)。

      executeBatch(): 将多条SQL语句在一次和数据库交互过程中使用。

PreparedStatement:

       addBatch(): 将当前参数内容交给PreparedStatement(将替换占位符的参数暂时保存在PreparedStatement维护的缓存中)。

       executeBatch(): 批处理执行,将多条记录的参数内容在一次和数据库交互过程中传输给数据库。

注意:在批处理中要设置手动提交事务,批处理执行后再提交事务。

  

如果不用批处理:

 public static void insertItems() {
	   Connection conn=null;
	   PreparedStatement ps=null;
	   int count=0;
	   try {
		   conn=ConnectionFactory.getConnection();
		   String sql="INSERT INTO Student VALUES(?,?,?)";
		   ps=conn.prepareStatement(sql);
		   long startTime=System.currentTimeMillis();
		   for (int i = 0; i < 10000; i++) {
			ps.setString(1, ""+i);
			ps.setString(2, "mao"+i);
			ps.setString(3, "男");
			ps.executeUpdate();
			count++;
		}
		   long endTime=System.currentTimeMillis();
		   long tm=endTime-startTime;
		   System.out.println("耗时:"+tm);
		   System.out.println("插入了:"+count+"条记录");
	   }catch(Exception e) {
		   e.printStackTrace();
		   try {
			conn.rollback();
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
	   }finally {
		   CloseDbUtils.closeConn(conn, ps);
	   }
   }
执行结果:

耗时:6719
插入了:10000条记录

批处理:

  public static void insertItemsByBatch() {
	   Connection conn=null;
	   PreparedStatement ps=null;
	   int count=0;
	   try {
		   conn=ConnectionFactory.getConnection();
		   conn.setAutoCommit(false);
		   String sql="INSERT INTO Student VALUES(?,?,?)";
		   ps=conn.prepareStatement(sql);
		   long startTime=System.currentTimeMillis();
		   for (int i = 0; i < 10000; i++) {
			ps.setString(1, ""+i);
			ps.setString(2, "mao"+i);
			ps.setString(3, "男");
			ps.addBatch();
			count++;
		}
		   ps.executeBatch();
		   conn.commit();
		   long endTime=System.currentTimeMillis();
		   long tm=endTime-startTime;
		   System.out.println("耗时:"+tm);
		   System.out.println("插入了:"+count+"条记录");
	   }
	   catch(Exception e) {
		   e.printStackTrace();
		   try {
			conn.rollback();
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
	   }
	   finally {
		   CloseDbUtils.closeConn(conn, ps);
	   }
   }

执行结果:

耗时:297
插入了:10000条记录
通过对比可以发现批处理可以很好的提升程序的执行效率。

猜你喜欢

转载自blog.csdn.net/start_mao/article/details/78719808
今日推荐