標籤:

用Python定時查詢MySQL資料庫並存儲到Excel中

用Python定時查詢MySQL資料庫並存儲到Excel中

日常工作中,經常需要隔一段時間去資料庫中查詢數據,雖然很簡單,但頻率過高也比較煩。因此考慮有沒有一種方法定時跑一遍SQL語句,並將結果存儲到Excel文件中。利用Python3的PyMySQL包和xlwt可以實現這一功能。以本地資料庫為例:

import pandas as pdimport timefrom datetime import datetimeimport pymysqlimport osimport xlwt# 定義從MySQL資料庫中取數的函數def Get_Data_From_MySQL(): db = pymysql.connect( host = 127.0.0.1, database = "world", user = "root", password = "******",# 此處password即MySQL資料庫密碼 port = 3306, charset = utf8 ) cursor = db.cursor() effect_row = cursor.execute( SELECT Code 編號, Name 名稱, Continent 所在大州,Region 國家,HeadOFState 首腦,Capital 首都 From world.country LIMIT 100 ) row_1 = cursor.fetchall()# 查詢結果存儲到Excel文件中 write_in_time = time.strftime(%Y%m%d_%H%M%S) workbook = xlwt.Workbook(encoding = utf-8) booksheet = workbook.add_sheet(write_in_time,cell_overwrite_ok = True) for i,field_desc in enumerate(cursor.description): booksheet.write(0,i,field_desc[0]) i +=1 for i,row in enumerate(row_1): for j,col in enumerate(row): booksheet.write(i+1,j,col) folder_name = os.path.abspath(rC:\Users\rjs\Desktop\查詢結果) # Excel文件存儲路徑 save_file_way = folder_name + r// +str(write_in_time)+ 本地資料庫查詢結果.xls # Excel文件名 workbook.save(save_file_way) while True: if datetime.now() < datetime(2018,5,10,23,59,59): #查詢截止時間為2018-5-10 23:59:59 Get_Data_From_MySQL() time.sleep(3600) #每隔一個小時查詢一次 else: print("已到截止時間,停止取數。") break

查詢結果如下:


推薦閱讀:

關係型資料庫 RDBMS 的舊與新 -- 談談 NewSQL
Spring整合SequoiaDB SQL
Spring事務管理
資料庫原理
Mysql學習第四篇:表的設計

TAG:SQL | 資料庫 |