当需要向数据库发送一批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做批处理。