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('公告链接信息无需更新') 
   
相关推荐
ACERT33320 小时前
05-矩阵理论复习第五章 向量与矩阵范数
python·算法·矩阵
春蕾夏荷_72829772520 小时前
c++ 将xml数据写入sqlite数据库
xml·数据库
workflower1 天前
时序数据获取事件
开发语言·人工智能·python·深度学习·机器学习·结对编程
廋到被风吹走1 天前
【数据库】【MySQL】InnoDB外键解析:约束机制、性能影响与最佳实践
android·数据库·mysql
C++业余爱好者1 天前
Java 提供了8种基本数据类型及封装类型介绍
java·开发语言·python
掘根1 天前
【消息队列】交换机数据管理实现
网络·数据库
Logic1011 天前
《Mysql数据库应用》 第2版 郭文明 实验6 数据库系统维护核心操作与思路解析
数据库·sql·mysql·学习笔记·计算机网络技术·形考作业·国家开放大学
AI Echoes1 天前
构建一个LangChain RAG应用
数据库·python·langchain·prompt·agent
@nengdoudou1 天前
KingbaseES支持 mysql 的find_in_set函数
数据库·mysql
派大鑫wink1 天前
从零到精通:Python 系统学习指南(附实战与资源)
开发语言·python