千万条数据批量插入数据库表

本文介绍了一种使用Java批量导入千万条记录到MySQL数据库的方法,仅用100秒即可完成,涉及连接配置、批量插入及事务管理技巧。

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

 通过最简单的方式将批量数据插入数据库中,千万条记录导入时间用了100s,贴出来代码供大家参考学习。


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;

/**
 * @Author BlueFire
 * @Date 2020/4/17 -22:13
 */
public class InsertTest {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        final String url = "jdbc:mysql://127.0.0.1:3306/mooding?autoReconnect=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai";
        final String name = "com.mysql.jdbc.Driver";
        final String user = "root";
        final String password = "123456";
        Connection conn = null;
        Class.forName(name); //指定连接类型
        conn = DriverManager.getConnection(url, user, password); //获取连接
        if (conn != null) {
            System.out.println("获取连接成功");
            insert(conn);//批量插入数据
        } else {
            System.out.println("获取连接失败");
        }

    }

    public static void insert(Connection conn) {
        // 开始时间
        Long begin = new Date().getTime();
        // sql前缀
        String prefix = "INSERT INTO t_users (id,t_name,t_password,sex,description,pic_url,school_name,regist_date,remark) VALUES ";
        try {
            // 保存sql后缀
            StringBuffer suffix = new StringBuffer();
            // 设置事务为非自动提交
            conn.setAutoCommit(false);
            // 比起st,pst会更好些
            PreparedStatement pst = (PreparedStatement) conn.prepareStatement("");
            //准备执行语句
            // 外层循环,总提交事务次数
            for (int i = 1; i <= 1000; i++) {
                suffix = new StringBuffer();
                // 第j次提交步长
                for (int j = 1; j <= 10000; j++) {
                    // 构建SQL后缀
                    suffix.append("('" + System.currentTimeMillis()* j + "','" + i * j + "','123456'" + ",'男'" + ",'教师'" + ",'www.bbk.com'" + ",'XX大学'" + ",'" + "2016-08-12 14:43:26" + "','备注'" + "),");
                }
                // 构建完整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("1000万条数据插入花费时间 : " + (end - begin) / 1000 + " s");
        System.out.println("插入完成");
    }
}
com.mysql.jdbc.PacketTooBigException: Packet for query is too large (4232009 > 4194304). You can change this value on the server by setting the max_allowed_packet’ variable.

如果遇到这样报错报错,是因为数据默认的max_allowed_packet 只有4M太小了,需要手动更改。

set global max_allowed_packet = 50*1024*1024* ;--这是设置为50M

记住,设置好后重新登录数据库才能看的设置后的值

show VARIABLES like '%max_allowed_packet%'

 

 

`flowVariablePoList` 是一种可能的命名约定,它可能是你在某个上下文中使用的变量名,这里的 "Po" 通常代 "Pojo"(Plain Old Java Object,简单Java对象),即用于映射数据库结构的Java实体类。当涉及到 MyBatisPlus 的批量插入时,你可以使用 `BatchInsert` 方法。 MyBatisPlus 提供了一个便捷的方式来处理大量数据批量插入,比如 `List<FlowVariablePo>` 类型的数据。以下是如何操作的示例: ```java import com.baomidou.mybatisplus.core.toolkit.OptimizeQuery condition; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.BaseService; // 假设 FlowVariablePo 是你的 Pojo 实体类 List<FlowVariablePo> flowVariablePoList = ... // 获取到1000条数据 // 如果你有一个 Service 接口,可以通过继承 BaseService 并重写对应的 insertAll 方法 class FlowVariableService extends BaseService<FlowVariablePo, FlowVariableMapper> { @Override public int insertAll(List<FlowVariablePo> list) { return super.insertList(list); } } // 或者如果你直接使用分页插件 PageHelper,可以在 Dao 层调用 public class FlowVariableDao { @Autowired private IFlowVariableMapper flowVariableMapper; // 自定义的 Mapper 接口 public void batchInsert(List<FlowVariablePo> poList) { Page<FlowVariablePo> page = new Page<>(1, 1000); // 创建Page对象,设置总页数为1示一次性插入所有数据 flowVariableMapper.batchInsert(page, poList); } } // 调用时 service.batchInsert(flowVariablePoList); ``` 在这个例子中,`insertList` 或 `batchInsert` 方法会一次性尝试将 `poList` 中的所有数据插入数据库,如果数据量大,这可能会提高性能,因为数据库通常对批量操作有优化。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值