最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python大批量寫入數(shù)據(jù)(百萬級(jí)別)的方法

 更新時(shí)間:2023年07月14日 10:15:15   作者:西紅市杰出青年  
這篇文章主要給大家介紹了關(guān)于Python大批量寫入數(shù)據(jù)(百萬級(jí)別)的相關(guān)資料,在日常處理數(shù)據(jù)的過程中,我們都有批量寫入數(shù)據(jù)的需求,文中給出了詳細(xì)的示例代碼,需要的朋友可以參考下

背景

現(xiàn)有一個(gè)百萬行數(shù)據(jù)的csv格式文件,需要在兩分鐘之內(nèi)存入數(shù)據(jù)庫。

方案

方案一:多線程+協(xié)程+異步MySql方案二:多線程+MySql批量插入

代碼

    1,先通過pandas讀取所有csv數(shù)據(jù)存入列表。
    2,設(shè)置N個(gè)線程,將一百萬數(shù)據(jù)均分為N份,以start,end傳遞給線程以切片的方法讀取區(qū)間數(shù)據(jù)(建議為16個(gè)線程)
    3,方案二 線程內(nèi)以  executemany 方法批量插入所有數(shù)據(jù)。
    4,方案一 線程內(nèi)使用異步事件循環(huán)遍歷所有數(shù)據(jù)異步插入。 
    5,方案一純屬?zèng)]事找事型。

方案二

import threading

import pandas as pd
import asyncio
import time

import aiomysql
import pymysql

data=[]
error_data=[]

def run(start,end):
    global data
    global error_data
    print("start"+threading.current_thread().name)
    print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
    mysdb = getDb("*", *, "*", "*", "*")
    cursor = mysdb.cursor()
    sql = """insert into *_*_* values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"""
    cursor.executemany(sql,data[start:end])
    mysdb.commit()
    mysdb.close()
    print("end" + threading.current_thread().name)
    print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))

def csv_file_read_use_pd(csvFile):
    csv_result = pd.read_csv(csvFile,encoding="utf-16",sep='\t')
    csv_result = csv_result.fillna(value="None")
    result = csv_result.values.tolist()
    return result

class MyDataBase:
    def __init__(self,host=None,port=None,username=None,password=None,database=None):
        self.db = pymysql.connect(host=host,port=port,user=username,password=password,database=database)
    def close(self):
        self.db.close()

def getDb(host,port,username,password,database):
    MyDb = MyDataBase(host, port, username, password,database)
    return MyDb.db

def main(csvFile):
    global data  #獲取全局對(duì)象  csv全量數(shù)據(jù)
    #讀取所有的數(shù)據(jù)   將所有數(shù)據(jù)均分成   thread_lens   份 分發(fā)給  thread_lens  個(gè)線程去執(zhí)行
    thread_lens=20
    csv_result=csv_file_read_use_pd(csvFile)
    day = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    for item in csv_result:
        item.insert(0,day)

    data=csv_result
    thread_exe_count_list=[]   #線程需要執(zhí)行的區(qū)間
    csv_lens=len(csv_result)
    avg = csv_lens // thread_lens
    remainder=csv_lens % thread_lens
    # 0,27517  27517,55,034
    nowIndex=0
    for i in range(thread_lens):
        temp=[nowIndex,nowIndex+avg]
        nowIndex=nowIndex+avg
        thread_exe_count_list.append(temp)
    thread_exe_count_list[-1:][0][1]+=remainder  #余數(shù)分給最后一個(gè)線程
    # print(thread_exe_count_list)

    #th(thread_exe_count_list[0][0],thread_exe_count_list[0][1])

    for i in range(thread_lens):
        sub_thread = threading.Thread(target=run,args=(thread_exe_count_list[i][0],thread_exe_count_list[i][1],))
        sub_thread.start()
        sub_thread.join()
        time.sleep(3)

if __name__=="__main__":
    #csv_file_read_use_pd("分公司箱型箱量.csv")
    main("分公司箱型箱量.csv")

方案一

import threading

import pandas as pd
import asyncio
import time

import aiomysql

data=[]
error_data=[]

async def async_basic(loop,start,end):
    global data
    global error_data
    print("start"+threading.current_thread().name)
    print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
    conn = await aiomysql.connect(
        host="*",
        port=*,
        user="*",
        password="*",
        db="*",
        loop=loop
    )
    day = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    sql = """insert into **** values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"""
    async with conn.cursor() as cursor:
        for item in data[start:end]:
            params=[day]
            params.extend(item)
            try:
                x=await cursor.execute(sql,params)
                if x==0:
                    error_data.append(item)
                print(threading.current_thread().name+"   result "+str(x))
            except Exception as e:
                print(e)
                error_data.append(item)
                time.sleep(10)
                pass
    await conn.close()
    #await conn.commit()
    #關(guān)閉連接池
    # pool.close()
    # await pool.wait_closed()
    print("end" + threading.current_thread().name)
    print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))

def csv_file_read_use_pd(csvFile):
    csv_result = pd.read_csv(csvFile,encoding="utf-16",sep='\t')
    csv_result = csv_result.fillna(value="None")
    result = csv_result.values.tolist()
    return result

def th(start,end):
    loop = asyncio.new_event_loop()
    loop.run_until_complete(async_basic(loop,start,end))


def main(csvFile):
    global data  #獲取全局對(duì)象  csv全量數(shù)據(jù)
    #讀取所有的數(shù)據(jù)   將所有數(shù)據(jù)均分成   thread_lens   份 分發(fā)給  thread_lens  個(gè)線程去執(zhí)行
    thread_lens=20
    csv_result=csv_file_read_use_pd(csvFile)
    data=csv_result
    thread_exe_count_list=[]   #線程需要執(zhí)行的區(qū)間
    csv_lens=len(csv_result)
    avg = csv_lens // thread_lens
    remainder=csv_lens % thread_lens
    # 0,27517  27517,55,034
    nowIndex=0
    for i in range(thread_lens):
        temp=[nowIndex,nowIndex+avg]
        nowIndex=nowIndex+avg
        thread_exe_count_list.append(temp)
    thread_exe_count_list[-1:][0][1]+=remainder  #余數(shù)分給最后一個(gè)線程
    print(thread_exe_count_list)

    #th(thread_exe_count_list[0][0],thread_exe_count_list[0][1])

    for i in range(thread_lens):
        sub_thread = threading.Thread(target=th,args=(thread_exe_count_list[i][0],thread_exe_count_list[i][1],))
        sub_thread.start()
        time.sleep(3)

if __name__=="__main__":
    #csv_file_read_use_pd("分公司箱型箱量.csv")
    main("分公司箱型箱量.csv")

總結(jié)

到此這篇關(guān)于Python大批量寫入數(shù)據(jù)的文章就介紹到這了,更多相關(guān)Python大批量寫入數(shù)據(jù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python配置文件解析模塊ConfigParser使用實(shí)例

    Python配置文件解析模塊ConfigParser使用實(shí)例

    這篇文章主要介紹了Python配置文件解析模塊ConfigParser使用實(shí)例,本文講解了figParser簡(jiǎn)介、ConfigParser 初始工作、ConfigParser 常用方法、ConfigParser使用實(shí)例等內(nèi)容,需要的朋友可以參考下
    2015-04-04
  • 使用Python實(shí)現(xiàn)炫酷的數(shù)據(jù)動(dòng)態(tài)圖大全

    使用Python實(shí)現(xiàn)炫酷的數(shù)據(jù)動(dòng)態(tài)圖大全

    數(shù)據(jù)可視化是通過圖形、圖表、地圖等可視元素將數(shù)據(jù)呈現(xiàn)出來,以便更容易理解、分析和解釋,它是將抽象的數(shù)據(jù)轉(zhuǎn)化為直觀形象的過程,本文給大家介紹了使用Python實(shí)現(xiàn)炫酷的數(shù)據(jù)動(dòng)態(tài)圖大全,需要的朋友可以參考下
    2024-06-06
  • Python+Seaborn繪制分布圖的示例詳解

    Python+Seaborn繪制分布圖的示例詳解

    這篇文章我們將介紹10個(gè)示例,從而幫助大家掌握如何使用Python中的Seaborn庫來創(chuàng)建圖表。文中示例代碼講解詳細(xì),感興趣的可以了解一下
    2022-05-05
  • Python 堆疊柱狀圖繪制方法

    Python 堆疊柱狀圖繪制方法

    這篇文章主要介紹了Python 堆疊柱狀圖繪制方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-07-07
  • Python操作PowerPoint實(shí)現(xiàn)添加與設(shè)置文本框完整教程

    Python操作PowerPoint實(shí)現(xiàn)添加與設(shè)置文本框完整教程

    在制作 PowerPoint 演示文稿時(shí),文本框是最常用的元素之一,本文將介紹如何使用 Python 在 PowerPoint 中添加文本框,并設(shè)置文本內(nèi)容、格式和邊距等屬性,希望對(duì)大家有所幫助
    2026-04-04
  • 解決Python圖形界面中設(shè)置尺寸的問題

    解決Python圖形界面中設(shè)置尺寸的問題

    這篇文章主要介紹了解決Python圖形界面中設(shè)置尺寸的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-03-03
  • Python操作列表常用方法實(shí)例小結(jié)【創(chuàng)建、遍歷、統(tǒng)計(jì)、切片等】

    Python操作列表常用方法實(shí)例小結(jié)【創(chuàng)建、遍歷、統(tǒng)計(jì)、切片等】

    這篇文章主要介紹了Python操作列表常用方法,結(jié)合實(shí)例形式總結(jié)分析了Python列表常見的創(chuàng)建、遍歷、統(tǒng)計(jì)、切片等操作技巧與相關(guān)注意事項(xiàng),需要的朋友可以參考下
    2019-10-10
  • python 窮舉指定長(zhǎng)度的密碼例子

    python 窮舉指定長(zhǎng)度的密碼例子

    這篇文章主要介紹了python 窮舉指定長(zhǎng)度的密碼例子,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-04-04
  • 基于Python和C++實(shí)現(xiàn)刪除鏈表的節(jié)點(diǎn)

    基于Python和C++實(shí)現(xiàn)刪除鏈表的節(jié)點(diǎn)

    這篇文章主要介紹了基于Python和C++實(shí)現(xiàn)刪除鏈表的節(jié)點(diǎn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-07-07
  • Flask創(chuàng)建并運(yùn)行數(shù)據(jù)庫遷移的實(shí)現(xiàn)過程

    Flask創(chuàng)建并運(yùn)行數(shù)據(jù)庫遷移的實(shí)現(xiàn)過程

    Flask創(chuàng)建并運(yùn)行數(shù)據(jù)庫遷移的過程是一個(gè)涉及多個(gè)步驟的操作,旨在幫助開發(fā)者在開發(fā)過程中管理數(shù)據(jù)庫模式的變化,而不需要手動(dòng)地刪除和重建數(shù)據(jù)庫表,從而避免數(shù)據(jù)丟失,以下是一個(gè)詳細(xì)的步驟說明,需要的朋友可以參考下
    2024-09-09

最新評(píng)論

洛阳市| 西峡县| 铁力市| 新竹县| 拉孜县| 霍山县| 荃湾区| 新郑市| 双桥区| 来宾市| 大足县| 巫溪县| 清流县| 青州市| 深圳市| 余庆县| 杭锦后旗| 夏邑县| 井陉县| 苏尼特左旗| 渑池县| 石柱| 秦皇岛市| 兴隆县| 曲麻莱县| 乡城县| 右玉县| 南开区| 阳西县| 稻城县| 乾安县| 图们市| 越西县| 承德县| 宿迁市| 荣昌县| 申扎县| 清水河县| 孟村| 枣庄市| 永济市|