zoukankan      html  css  js  c++  java
  • 使用JDBC进行批处理

    http://mousepc.iteye.com/blog/1131462


    业务场景当需要向数据库发送一批SQL语句执行时,应避免向数据库一条条的发送执行,而应采用JDBC的批处理机制,以提升执行效率。
    实现批处理有两种方式: 


    第一种方式:使用 Statement.addBatch(sql)

    Connection conn = JdbcUtil.getConnection();
    String sql1 = "insert into user(name,password,email,birthday) values('kkk','123','abc@sina.com','1978-08-08')";
    String sql2 = "update user set password='123456' where id=3";
    Statement st = conn.createStatement();
    st.addBatch(sql1);  //把SQL语句加入到批命令中
    st.addBatch(sql2);  //把SQL语句加入到批命令中
    st.executeBatch();



    采用Statement.addBatch(sql)方式实现批处理:
    •优点:可以向数据库发送多条不同的SQL语句。
    •缺点:
    •SQL语句没有预编译。
    •当向数据库发送多条语句相同,但仅参数不同的SQL语句时,需重复写上很多条SQL语句。例如:

      Insert into user(name,password) values(‘aa’,’111’);

      Insert into user(name,password) values(‘bb’,’222’);

      Insert into user(name,password) values(‘cc’,’333’);

      Insert into user(name,password) values(‘dd’,’444’);



    第二种方式:PreparedStatement.addBatch()
    Connection conn = JdbcUtil.getConnection();
    String sql = "insert into user(name,password,email,birthday) values(?,?,?,?)";
    PrepareStatement st = conn.prepareStatement(sql);
    for(int i=0;i<50000;i++){
        st.setString(1, "aaa" + i);
        st.setString(2, "123" + i);
        st.setString(3, "aaa" + i + "@sina.com");
        st.setDate(4,new Date(1980, 10, 10));
        st.addBatch();
        if(i%1000==0){
            st.executeBatch();
            st.clearBatch();
        }
    }
    st.executeBatch();

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

  • 相关阅读:
    在业务层进行回滚操作时如何避免回滚指令冗余
    云计算VS大数据 记与思
    [SAPBI]解决:不存在源系统(逻辑系统) T90CLNT090 的源系统标识符
    物料分类账简介
    BW Query设计中公式冲突解决方案
    解决BW处理链中节点有选择的执行
    如何立即手动执行BW周期性处理链
    资产数据源抽取当日增量数据的配置说明
    文本数据源预览出错
    主数据上载因重复记录报错问题解决
  • 原文地址:https://www.cnblogs.com/leeeee/p/7276077.html
Copyright © 2011-2022 走看看