批处理

JDBC 批处理:

当需要向数据库发送一批 SQL 语句执行时,应避免向数据库一条条的发送执行,而应采用 JDBC 的批处理机制,以提升执行效率。

实现批处理有两种方式

  • 第一种方式:
  • statement 批处理
@Test
public void show(){
	Connection conn =null;
	Statement stmt = null;
	 try {
		conn = JDBCUtil.getConnection();
		stmt = conn.createStatement();  
		 //添加批次
		  for(int i = 1 ;i <=10000 ; i++){
				String sql ="insert into
		  		tb_user(username,password)values( '"+i+"','19')";
				 stmt.addBatch(sql);
			  //一次性向数据库添加 3000
				 if(i%3000 == 0){ 
				 //执行批次
						 stmt.executeBatch();
							  //清空批次
					    stmt.clearBatch();
 					}
					 } 
				   /执行余下批次
				stmt.executeBatch(); 
 				  //清空批次
			   stmt.clearBatch();
 } catch (SQLException e) { e.printStackTrace();
 }finally{
JDBCUtil.close(conn, stmt);
  }
}

Statement.addBatch(sql)

执行批处理 SQL 语句

executeBatch()方法:执行批处理命令

clearBatch()方法:清除批处理命令

采用 Statement.addBatch(sql)方式实现批处理:

优点:可以向数据库发送多条不同的 sql 语句。
缺点: SQL 语句没有预编译。当向数据库发送多条语句相同,但仅参数不同的
SQL 语句时,需重复写上很多条 SQL 语句。例如:

Insert into user(name,password) values(‘aa’,’111’);

Insert into user(name,password) values(‘bb’,’222’);

Insert into user(name,password) values(‘cc’,’333’);

Insert into user(name,password) values(‘dd’,’444’);
  • 第二种方式:

  • preparestatement 批处理

  • 优点:

  • 发送的是与编译后的sql语句,执行效率高

  • 缺点:

  • 只能应用在sql语句相同,但是参数不同的批处理中,因此此种形式的批处理经常用于在同一表中批量插入相同的数据,或者批量更新表中的数据。

     	PreparedStatement ps = null;
     	Connection con = null;
     	Savepoint sp = null;
     	try{
     	con = TestC3P0.getConnectionTest();
     	String sql = "insert into bank(name,money) values(?,?)";
     	ps = con.prepareStatement(sql);
     	con.setAutoCommit(false);
     	for (int i = 0; i < 100; i++) {
     		ps.setString(1, "xrn");
     		ps.setDouble(2, 100);
     		
     		ps.addBatch();
     		if (i%30 ==0) {
     			ps.executeBatch();//批处理,一次三十条
     			ps.clearBatch();//清理批处理
     		}
     	}
     	ps.executeBatch();//存入剩余的数据
     	ps.clearBatch();
     	con.commit();
     	}catch(Exception a){
     		a.printStackTrace();
     	}finally{
     		try {
     			con.setAutoCommit(true);
     		} catch (SQLException e) {
     			// TODO Auto-generated catch block
     			e.printStackTrace();
     		}
     	}
    

两种批处理的区别:

1.prestatement的效率比前者高
2.在使用PreparedStatement对象执行SQL命令时,命令被数据库进行编译和解析,然后被放到命令缓冲区.然后,每当执行同一个PreparedStatement对象时,它就会被再解析一次,但不会被再次编译.在缓冲区中可以发现预编译的命令,并且可以重新使用.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值