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

11 篇文章 0 订阅
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值