package com.storge;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
import org.junit.Test;
/* *jdbc的批处理有两种机制。
*第一种 方式:使用Statement接口的批处理,
*addBatch(sql);将第一条sql加入批处理。
*executeBatch()执行批处理。
*clearBatch()清楚批处理的缓存
*
*第二种方式为:
*使用PreparedStatement进行批处理。
*好处,如果连续执行多个结构吸纳共同的sql----采用预编译---sql只需编译一次,
*/
public class Batch {
@Testpublic void test1() {
// 第一种方式。使用Statement接口的批处理操作。
// 批处理操做一般没有查询语句,一般为insert update delete
Connection con = null;
Statement st = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_database10", "root","wdl03707552882");
con.setAutoCommit(false);
st = con.createStatement();
// 连续执行多条语句
st.addBatch("use mytest");
st.addBatch("insert into mytable values(1,'xin')");
st.addBatch("insert into mytable values(2,'zhangsan')");
st.addBatch("insert into mytable values(3,'liuming')");
st.executeBatch();
con.commit();
} catch (Exception a) {
a.printStackTrace();
} finally {
st.close();
con.close();
}
}
@Test
public void test2(){
long start =(int)System.currentTimeMillis();
//以第二种方式进行批量操作,
//向mysql数据库中通过preparedStatement插入5000条数据。
Connection con=null;
PreparedStatement st=null;
String sql="insert into person values(?,?,?)";
try{
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mytest","root","wdl03707552882");
con.setAutoCommit(false);
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();
con.commit();
//清空已有的sql
st.clearBatch();
}
}
//为了确保缓存没有sql语句未被执行
st.executeBatch();
con.commit();
long end=(int )System.currentTimeMillis();
}catch(Exception a){
a.printStackTrace();
}finally {
st.close();
con.close();
}
}
/**采用PreaparedStatement.addBatch()实现批处理
*优点:发送的是预编译的sql语句。执行效率高。
*缺点:只能应用到sql语句相同,但参数不同的批处理中,因此此种像是的批处理经常用于在同一个表中
*批量插入数据或者批量更新数据。
*/
参考:https://blog.csdn.net/uniqueweimeijun/article/details/54139955