python:大文件分批/块导入数据库方式记录

一、问题背景

对于数据文件比较大的数据,一次性串联sql进行入库,往往会受到数据库本身对sql长度的限制,从而需要分块或者分批次,将大数据文件一点一点的进行入库。特针对这种入库方式,进行一个简单记录,各类数据库入库后续均可参考下述实现分块的方式,进行分批入库数据。

二、实现记录

问题点其实主要是如何对数据进行分块。pyhton的read_csv函数和read_excel等数据读取函数都含有分批读取数据的参数:chunksize,从而实现分批入库。

如果是已经全部读取了数据,还想再进一步分批,则可以参考下述代码进行分批读取:

python 复制代码
batch_size = 2000
total_rows = p_result_notice_mes_df.shape[0]    
total_batches = total_rows // batch_size + (1 if total_rows % batch_size > 0 else 0)
for i in range(total_batches):
        start_index = i * batch_size
        end_index = min((i + 1) * batch_size, total_rows)
        batch_df = p_result_notice_mes_df.iloc[start_index:end_index]

部分示例程序如下:

python 复制代码
third_tbname ='bods.scw_info'
    # 计算数据总数和批次数
    batch_size = 2000
    total_rows = p_result_notice_mes_df.shape[0]    
    total_batches = total_rows // batch_size + (1 if total_rows % batch_size > 0 else 0)
    if p_third_flag:
        for i in range(total_batches):
            start_index = i * batch_size
            end_index = min((i + 1) * batch_size, total_rows)
            batch_df = p_result_notice_mes_df.iloc[start_index:end_index]
       
            third_values_list = []
            cursor.execute(f"truncate table {third_tbname} ")
            # 构建批量插入的SQL语句        
            insert_query = f"""
                        INSERT into {third_tbname} (changelog_id, notice_model, notice_batch,
                                                    brand, vehicle_type, rated_quality, total_quality, 
                                                    curb_weight, fuel_type, emission_standard)        
                            VALUES 
                            """
            for index, row in batch_df.iterrows():
                third_values_list.append(f"""('{row["变记录"]}' , '{row["告"]}', '{row["公次"]}', 
                                         '{row["品牌"]}', '{row["类型"]}', '{row["额量"]}', '{row["总"]}',
                                         '{row["整量"]}', '{row["燃类"]}', '{row["排放准"]}'
                                         )""")
            
            insert_query += ',\n'.join(third_values_list)
                        
            # 执行批量插入
            cursor.execute(insert_query) 
        print('公告url信息更新入库成功!\n')  
    else:
        print('公告链接信息无需更新') 
   
相关推荐
leisoo80975 分钟前
100GBA股股票数据怎么存ClickHouseRedisMySQLJSON完整对比
大数据·linux·服务器·开发语言·python
WangYan202215 分钟前
基于XGBoost与AI的生态—地学多源数据建模:植被与土地利用识别、土壤碳氮空间预测、生物多样性驱动机制、土壤微生物功能预测、生态退化与风险识别
python·机器学习·xgboost
ltl1 小时前
Disaggregated DB 合集:Socrates、PolarDB、Taurus 的共同模式
数据库
金銀銅鐵3 小时前
[Python] 借助 turtle 逐字展示唐诗《金缕衣》
python
Blossom i3 小时前
大数据预处理与采集实验一:使用Python操作MySQL数据库
数据库·mysql
雾时之林4 小时前
Linux--软件管理、源码包安装
linux·服务器·数据库
Python大数据分析@5 小时前
使用大模型MCP采集数据,爬虫已经无门槛
python·网络爬虫
quantdash_cc5 小时前
告别自建 Requests/BS4 网页爬虫:基于 QuantDash 搭建零维保的高性能量化行情流水线
开发语言·爬虫·python·pandas·量化·quantdash
65岁退休Coder5 小时前
LangChain v1.3.4 笔记 - 07 补充:链式调用 LCEL
后端·python·langchain
卷无止境5 小时前
FastAPI 部署在 Nginx 后面到底该怎么配
后端·python