实现数据库的批处理两种方式,以及比较其优缺点

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只需编译一次,
 *案例:
 *像数据库中添加5000条记录。
 *create table person(id int primary key,name varchar(30),email varchar(100));
 *
 *
 *con=DriverManager.getConnection(url,name,password);
 *String sql="insert into table(name,password,email,birthday) values(?,?,?,?)";
 *st=con.prepareStatement(sql);
 *for(int i=0;i<5000;i++){
 * st.setString(1,"aaa"+i);
 * st.setString(2,"bbb"+i);
 * st.setString(3,"ccc"+i);
 * st.setData(4,new Date(1980,10,10);
 *st.addBatch();
 *if(i%1000==0){
 * st.executeBatch();
 *st.clearBatch();
 *}
 *}
 *
 * */
public class Batch {
@Test
public void test1() {
// 第一种方式。使用Statement接口的批处理操作。
// 批处理操做一般没有查询语句,一般为insert update delete

Connection con = null;
Statement st = null;
try {
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/db_database10", "root",
"wdl03707552882");
st = con.createStatement();
// 连续执行多条语句
st.addBatch("use mytest");
// st.addBatch("create table mytable(id int primary key,name varchar(20))");
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();
st.close();
con.close();
} catch (Exception a) {
a.printStackTrace();
} finally {


}


}


@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");
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();
}


}
}
/ *
*采用PreaparedStatement.addBatch()实现批处理
*优点:发送的是预编译的sql语句。执行效率高。
*缺点:只能应用到sql语句相同,但参数不同的批处理中,因此此种像是的批处理经常用于在同一个表中
*批量插入数据或者批量更新数据。

*/ s
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

uniquewdl

匆忙的人生,总有你喜欢的文章

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

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

打赏作者

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

抵扣说明:

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

余额充值