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('公告链接信息无需更新') 
   
相关推荐
默_笙3 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
qq_426003963 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫3 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技3 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读3 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
这个DBA有点耶3 天前
MVCC深入:Read View、版本链与快照读——InnoDB并发控制的内核
数据库·mysql·架构
DBA_G3 天前
从地面到云霄:GBase数据库在民航三大场景的落地实践
数据库
自由能燃气设备3 天前
商用全预混低氮冷凝锅炉免费方案vs付费方案对比+选型避坑指南
大数据·数据库·人工智能
只睡四小时3 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
科创致远3 天前
科创致远 ESOP 系统核心效能与实战价值展示
大数据·数据库·人工智能·精益工程