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('公告链接信息无需更新') 
   
相关推荐
曲幽2 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程6 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪6 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook7 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田20 小时前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python
jiayou641 天前
KingbaseES 实战:深度解析数据库对象访问权限管理
数据库
阿尔的代码屋1 天前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python