[英]python and mysql downloading data into a csv
即時通訊使用python熊貓並將mysql查詢存儲到數據幀中,然后將結果下載到excel文件中
query = """ ... """
DF= pd.read_sql(query, connection)
writer = pd.ExcelWriter('excel.xlsx',engine='xlsxwriter')
DF.to_excel(writer,'sheet1')
writer.save()
但是,當我需要更新文件時,我必須運行SQL查詢來檢索所有現有數據+新行,這每次可能要花一些時間才能執行,並且會使服務器不必要的負載
因此,例如,我有一個包含100行的excel文件,而數據庫有110行,我將運行查詢以從數據庫中檢索第90行到第110行的數據,並使用其他10行更新excel
謝謝
檢查文件是否存在,然后寫入文件
import os
exists = os.path.exists(file) # check if the file already exists
df=pd.read_sql(query, connection) #read the data using limit or offset here
open_mode = None
if exists:
open_mode = 'a'
header = False
else:
open_mode = 'w'
header = True
with open(file, open_mode) as f:
df.to_excel(f, header=header, index=False)
有幾種方法可以做到這一點。 首先,您需要在excel中讀取數據,即將現有數據加載到數據框中。 另一種選擇是將指針存儲在某個位置,例如,數據框中的行數或數據庫中的最后一個id(假設您可以使用auto_increment
鍵),然后相應地修改查詢。 例如,將最后一個ID(例如1000)存儲在文件中。 然后閱讀並從那里繼續前進。
with open('last_id') as f:
last_id = f.read()
sql = "SELECT * FROM `mytable` WHERE `id` > %d" % last_id
或者,存儲提取數據的大小並使用offset語法 。
然后,這只是連接兩個數據幀(現有+新)的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.