• <十二>JDBC_批量处理


    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import org.junit.Test;
    import com.kk.jdbc.JDBCTools;

    public class JDBCTest {

     /*
      * 向表中插入多条记录
      */
     @Test
     public void testBatchWithStatement() {

      Connection con = null;
      PreparedStatement ps = null;
      String sql = null;

      try {

       con = JDBCTools.getConnection();
       JDBCTools.beginTx(con);

       sql = "insert into users values (?,?,?,?)";

       ps = con.prepareStatement(sql);

       long begin = System.currentTimeMillis();

       for (int i = 0; i < 1000; i++) {
        ps.setInt(1, i + 1);
        ps.setString(2, "name_" + i);
        ps.setString(3, "pass_" + i);
        ps.setInt(4, i++);
        ps.executeUpdate();
       }
       long end = System.currentTimeMillis();
       System.out.println("Time:" + (end - begin));
       JDBCTools.commit(con);

      } catch (Exception e) {
       JDBCTools.rollback(con);
      } finally {
       JDBCTools.release(null, ps, con);
      }
     }

     @Test
     public void testBatch() {

      Connection con = null;
      PreparedStatement ps = null;
      String sql = null;

      try {

       con = JDBCTools.getConnection();
       JDBCTools.beginTx(con);

       sql = "insert into users values (?,?,?,?)";

       ps = con.prepareStatement(sql);

       long begin = System.currentTimeMillis();

       for (int i = 0; i < 1000; i++) {
        ps.setInt(1, i + 1);
        ps.setString(2, "name_" + i);
        ps.setString(3, "pass_" + i);
        ps.setInt(4, i++);
        
        //积攒SQL,当积攒到30就统一执行一次,并清空
        ps.addBatch();
        
        if ((i+1)%30==0) {
         ps.executeBatch();
         ps.clearBatch();
        }
       }
       
       //若总条数不是批量数的整条数,则还需要再额外执行一次
       if (1000%300!=0) {
        ps.executeBatch();
        ps.clearBatch();
       }
       
       long end = System.currentTimeMillis();
       System.out.println("Time:" + (end - begin));
       JDBCTools.commit(con);

      } catch (Exception e) {
       JDBCTools.rollback(con);
      } finally {
       JDBCTools.release(null, ps, con);
      }
     }
    }

  • 相关阅读:
    【LeetCode】13. 罗马数字转整数
    【LeetCode】9. 回文数
    【LeetCode】7. 整数反转python3
    【LeetCode】7. 整数反转
    【LeetCode】1. 两数之和
    拖拽选择区域日历组件
    gitlab之gitlab-ci自动部署
    GitLab 安装和配置
    移动端键盘弹起导致底部按钮上浮解决方案
    JS判断滚动条是否停止滚动
  • 原文地址:https://www.cnblogs.com/iamkk/p/6092148.html
Copyright © 2020-2023  润新知