1亿条数据添加《mysql》

本文介绍了一种使用Java和MySQL数据库进行大规模数据批量插入的方法,通过多线程并发执行,提高了数据插入效率。文章详细展示了如何创建数据库连接,构建SQL语句,并利用PreparedStatement执行批处理插入,最后分析了整个过程的执行时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.cz.hs;

import org.springframework.util.StringUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
/**

  • @Author Kevin

  • @Date 2019/11/28 10:49

  • @Version 1.0
    */
    public class InsertTest {
    static long count = 100_000_000;
    static int threadsize = 2;

    static class InsertDb {
    Connection conn = null;
    private int persize = 200_000;

     public  void initConn() throws ClassNotFoundException, SQLException {
    
         String sql;
         String url = "jdbc:mysql://localhost:3306/abcuser=root&password=root&useUnicode=true&characterEncoding=UTF8&useSSL=false&serverTimezone=UTC";
         try {
             // 之所以要使用下面这条语句,是因为要使用MySQL的驱动,所以我们要把它驱动起来,
             // 可以通过Class.forName把它加载进去,也可以通过初始化来驱动起来,下面三种形式都可以
             Class.forName("com.mysql.jdbc.Driver");// 动态加载mysql驱动
    
             System.out.println("成功加载MySQL驱动程序");
             // 一个Connection代表一个数据库连接
             conn = DriverManager.getConnection(url);
         } catch (Exception e) {
             e.printStackTrace();
         }
     }
    

/*
public String randomStr(int size) {
//定义一个空字符串
String result = “”;
for (int i = 0; i < 6; ++i) {
//生成一个97~122之间的int类型整数
int intVal = (int) (Math.random() * 26 + 97);
//强制转换(char)intVal 将对应的数值转换为对应的字符
//将字符进行拼接
result = result + (char) intVal;
}
//输出字符串
return result;
}*/

    public  void insert() {
        // 开时时间
        Long begin = new Date().getTime();
        // sql前缀
        String prefix = "INSERT INTO abc.`hs_project_plan` ( `jhzt`, `jhbh`, `jhnd`, `jhyd`, `xmmc`, `jhlb`,`xmlb`, `jhgly`, `bxsj`, `sjdw`, `xmzz`, `xmksrq`, `xmjsrq`, `create_date`, `create_by`, `del_flag`, `xmjd`, `gdzt`, `bz`) VALUES";

        try {
            // 保存sql后缀
            StringBuffer suffix = new StringBuffer();
            // 设置事务为非自动提交
            conn.setAutoCommit(false);
            //      Statement pst = conn.createStatement();
            // 比起st,pst会更好些
            PreparedStatement pst = conn.prepareStatement("");
            // 外层循环,总提交事务次数
            for (int i = 1; i <= count / persize /threadsize; i++) {
                // 第次提交步长
                for (int j = 1; j <= persize; j++) {
                    // 构建sql后缀
                suffix.append("('01','总公司-2019001',2019,1,'亿条测试项目','02','5','342','2019-09-06','1','342','2019-09-07','2019-09-08','2019-09-09','342',0,'01','01','项目描述'),");
                }
                // 构建完整sql
                String sql = prefix + suffix.substring(0, suffix.length() - 1);
                // 添加执行sql
                pst.addBatch(sql);
                // 执行操作
                pst.executeBatch();
                // 提交事务
                conn.commit();
                // 清空上一次添加的数据
                suffix = new StringBuffer();
            }
            // 头等连接
            pst.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 结束时间
        Long end = new Date().getTime();
        // 耗时
        System.out.println("cast : " + (end - begin) / 1000f + " ms");
    }

}



public static void main(String[] args) throws SQLException, ClassNotFoundException, InterruptedException {


    long s = System.currentTimeMillis();
    List<Thread> list = new ArrayList<>();
    for (int i = 0; i < threadsize; i++) {
        Thread th = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    InsertDb db = new InsertDb();
                    db.initConn();
                    db.insert();

                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (SQLException e) {
                    e.printStackTrace();
                }

            }
        });
        th.start();
        list.add(th);
    }
    for(Thread th : list){
        th.join();
    }

    long e = System.currentTimeMillis();
    System.out.println("total耗时"+(e -s)/1000f+"s");
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值