批处理就是一批一批的处理,而不是一个一个的处理。mysql
当你有10条sql语句要执行时,一次向服务器发送一条语句,这么作效率不好。处理的方案是用批处理,即一次向服务器发送多条sql语句,而后由服务器一次性处理。sql
批处理只针对更新(增、删、改),没有查询什么事。缓存
添加批的语句:PreparedStatement.addBatch();
执行批的语句:PreparedStatement.executeBatch();服务器
mysql默认批处理是关闭的,须要在url参数后面加上?rewriteBatchedStatement=true;url
示例:get
Connection con=null;
PreparedStatement st=null;
String sql="insert into person values(?,?,?)";
try{
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mytest","root","wdl03707552882");
st=con.prepareStatement(sql);//进行预编译
for(int i=1;i<=5000;i++){
st.setInt(1,i);
st.setString(2,"name"+i);
st.setString(3,"email"+i);
st.addBatch();
if(i%1000==0){
st.executeBatch();
//清空已有的sql
st.clearBatch();
}
}
//为了确保缓存没有sql语句未被执行
st.executeBatch();
long end=(int )System.currentTimeMillis();
}
catch(Exception a){
a.printStackTrace();
}
}
}it
/*
*采用PreaparedStatement.addBatch()实现批处理
*优势:发送的是预编译的sql语句。执行效率高。
*缺点:只能应用到sql语句相同,但参数不一样的批处理中,所以此种像是的批处理常常用于在同一个表中
*批量插入数据或者批量更新数据。
*/sio