用JDBC进行批处理

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

实现批处理有两种方式,第一种方式:
Statement.addBatch(sql)  list
执行批处理SQL语句
executeBatch()方法:执行批处理命令
clearBatch()方法:清除批处理命令

实现批处理的第一种方式(Statement方式):

 

package cn.itcast.jdbc;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import org.junit.Test;
import cn.itcast.utils.JdbcUtils;
/*
 create table testbatch
(
 	id int primary key,
 	name varchar (40)
);
 */
public class Demo3 {
	//实现批处理的第一种方式
	@Test
	public void test1() throws Exception{
		Connection conn =null;
		Statement st =null;	
		ResultSet rs =null;
		try
		{		
			conn  =JdbcUtils.getConnection();
			String sql= "insert into testbatch(id,name) values (3,'aaaa')";
			String sq2= "update testbatch set name='ccccd' where id=3";
			st=conn.createStatement();
			st.addBatch(sql);//把sql语句加载到statement维护的集合中
			st.addBatch(sq2);
			st.executeBatch(); //返回数组,数组中的元素用来保存执行sql语句影响的行数
		}catch (Exception e){
			e.printStackTrace();
		}finally{	
			JdbcUtils.release(conn, st, rs);
		}
	}
}


 

采用以上方式实现批处理:

优点:   可以向数据库发送多条不同的SQL语句。

缺点:  SQL语句没有预编译。

               当向数据库发送多条语句相同,但仅参数不同的SQL语句时,需重复写上很多sql语句。例如:

                  Insert into user(name,password) values('aa','111111');

                  Insert into user(name,password) values('bb','222222');

                  Insert into user(name,password) values('cc','333333');

 

实现批处理的第二种方式(PreparedStatement方式):

 

	//实现批处理的第二种方式
	@Test
	public void test2(){
		//记录时间
		long starttime=System.currentTimeMillis();
		
		Connection conn =null;
		PreparedStatement st =null;	
		ResultSet rs =null;
		try
		{		
			conn  =JdbcUtils.getConnection();
			String sql= "insert into testbatch(id,name) values (?,?)";
			st=conn.prepareStatement(sql);
			for(int i=0;i<100000;i++){  //加入10万条数据
				st.setInt(1,i);
				st.setString(2,"aa"+1);
				st.addBatch();   //把这条sql加入到集合中
				if(1%1000==0){
					st.executeBatch();//每次执行1000条sql语句
					st.clearBatch();	//清除sql语句以循环下一批sql语句
				}
			}
			st.executeBatch();
		}catch (Exception e){
			e.printStackTrace();
		}finally{	
			JdbcUtils.release(conn, st, rs);
		}
		//结束时间
		long endtime =System.currentTimeMillis();
		System.out.println("共花费:"+(endtime-starttime)/1000+"秒");
	}

结论:如果执行的sql语句是不一样的,那就用Statement做批处理。

            如果执行的sql语句是一样的,那就用PreparedStatement做批处理。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

傅荣康

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值