JDBC操作MySQL进行批处理

1、批处理:

概念:一次向数据库发送多条SQL语句,降低与数据库的交互次数,提升数据库层执行效率。

2、建表:

 

create database day16;

create table user
(
	id int primary key,
	name varchar(20)
);

3、测试:


我已经把数据库连接代码封装好了,在这里直接使用。如果你还没封装,参见我上篇博客。


    1)

	@Test
	//插入两条数据,删除第一条。使用Statement批处理
	public void text1(){
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		
		try{
			conn = JDBCUtil.getConnection();
			stmt = conn.createStatement();
			
			String sql1 = " insert into user(id,name) values(1,'张三') ";
			String sql2 = " insert into user(id,name) values(2,'李四') ";
			String sql3 = " delete from user where id = 1 ";
		
			
			stmt.addBatch(sql1);           //把三条语句加入批量处理的缓存
			stmt.addBatch(sql2);
			stmt.addBatch(sql3);        
			
			stmt.executeBatch();          //执行批处理

		
		}catch(Exception e){
			throw new RuntimeException(e);
		}finally{
			JDBCUtil.release(rs, stmt, conn); //关闭数据库资源
		}
	}
	

执行结果:

   2)

	@Test
	//插入10条数据 使用PreparedStatement
	
	public void text2(){
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		
		try{
			conn = JDBCUtil.getConnection();
			stmt = conn.prepareStatement(" insert into user(id,name) values(?,?)");
		
			for (int i = 1; i <= 10; i++) {
				stmt.setInt(1, i+1);
				stmt.setString(2,"aa"+(i+1));
				stmt.addBatch();  //向缓存中插入参数。
			}
			
			stmt.executeBatch();          //执行批处理

		
		}catch(Exception e){
			throw new RuntimeException(e);
		}finally{
			JDBCUtil.release(rs, stmt, conn); //关闭数据库资源
		}
	}
执行结果:


3)

      @Test
	//插入1000条数据 使用PreparedStatement
	//由于数据量过大,把每100条数据进行一个批处理
	public void text3(){
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		
		try{
			conn = JDBCUtil.getConnection();
			stmt = conn.prepareStatement(" insert into user(id,name) values(?,?)");
		
			for (int i = 0; i <= 1000; i++) {
				stmt.setInt(1, i+1);
				stmt.setString(2,"aa"+(i+1));
				
				stmt.addBatch();   				//向缓存中插入参数。
				if(i % 100 == 0){
					stmt.executeBatch();          //执行批处理
					stmt.clearBatch();          //清空缓存
				}
			}
			
			stmt.executeBatch();          //执行批处理 (如果执行了1001数据,最后一条数据在这里执行)

		}catch(Exception e){
			throw new RuntimeException(e);
		}finally{
			JDBCUtil.release(rs, stmt, conn); //关闭数据库资源
		}
	}


执行结果:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值