• 使用Batch批量添加数据


    package com.atguigu.jdbc;

    import java.sql.Connection;
    import java.sql.Date;
    import java.sql.PreparedStatement;
    import java.sql.Statement;

    import org.junit.Test;

    public class JDBCTest {
    @Test
    public void testBatch(){
    Connection connection=null;
    PreparedStatement preparedStatement=null;
    try{
    connection=JDBCTools.getConnection();
    JDBCTools.beginTx(connection);
    String sql="insert into customers values(?,?,?)";
    preparedStatement=connection.prepareStatement(sql);
    long beginTime=System.currentTimeMillis();
    for(int i=0;i<100000;i++){

    preparedStatement.setInt(1,i+100001);
    preparedStatement.setString(2, "");
    preparedStatement.setDate(3, new Date(new java.util.Date().getTime()));
    //preparedStatement.executeUpdate();
    //积攒SQL
    preparedStatement.addBatch();
    //当积攒到一定程度,就统一的执行一次,并且清空先前积攒的SQL
    if((i+1)%300==0){
    preparedStatement.executeBatch();
    preparedStatement.clearBatch();
    }
    }
    //若总条数不是批量数值的整数倍,则还需要再额外执行一次
    if((100000%300)!=0){
    preparedStatement.executeBatch();
    preparedStatement.clearBatch();
    }
    long stopTime=System.currentTimeMillis();
    JDBCTools.commit(connection);
    System.out.println(beginTime-stopTime);
    }catch(Exception e){
    e.printStackTrace();
    JDBCTools.rollback(connection);
    }finally{
    JDBCTools.release(null, preparedStatement, connection);
    }
    }

    @Test
    public void testBatchWithPreparedStatement(){
    Connection connection=null;
    PreparedStatement preparedStatement=null;
    try{
    connection=JDBCTools.getConnection();
    JDBCTools.beginTx(connection);
    String sql="insert into customers values(?,?,?)";
    preparedStatement=connection.prepareStatement(sql);
    long beginTime=System.currentTimeMillis();
    for(int i=0;i<100000;i++){

    preparedStatement.setInt(1,i+100001);
    preparedStatement.setString(2, "");
    preparedStatement.setDate(3, new Date(new java.util.Date().getTime()));
    preparedStatement.executeUpdate();
    }
    long stopTime=System.currentTimeMillis();

    JDBCTools.commit(connection);
    System.out.println(beginTime-stopTime);
    }catch(Exception e){
    e.printStackTrace();
    JDBCTools.rollback(connection);
    }finally{
    JDBCTools.release(null, preparedStatement, connection);
    }
    }

    }

  • 相关阅读:
    PHP工具下载地址
    Eclipse开发PHP环境配置
    Windows下搭建PHP开发环境
    无插件Vim编程技巧
    mvn详解
    Python读写文件
    python 大文件以行为单位读取方式比对
    insert时出现主键冲突的处理方法【转载】
    Python机器学习——线性模型
    机器学习算法与Python实践之(七)逻辑回归(Logistic Regression)
  • 原文地址:https://www.cnblogs.com/xiaona19841010/p/5204359.html
Copyright © 2020-2023  润新知