1. 程式人生 > 資料庫 >使用Python將Mysql的查詢資料匯出到檔案的方法

使用Python將Mysql的查詢資料匯出到檔案的方法

mysql官方提供了很多種connector,其中包括python的connector。

下載地址在:http://dev.mysql.com/downloads/connector/python/

直接安裝即可。

在python中:

1. 連線:

import mysql.connector
cnx = mysql.connector.connect(user='scott',password='tiger',host='127.0.0.1',database='employees')
cnx.close()

2. 查詢:

import datetime
import mysql.connector
cnx = mysql.connector.connect(user='scott',database='employees')
cursor = cnx.cursor()
query = ("SELECT first_name,last_name,hire_date FROM employees "
     "WHERE hire_date BETWEEN %s AND %s")
hire_start = datetime.date(1999,1,1)
hire_end = datetime.date(1999,12,31)
cursor.execute(query,(hire_start,hire_end))
for (first_name,hire_date) in cursor:
 print("{},{} was hired on {:%d %b %Y}".format(
  last_name,first_name,hire_date))
cursor.close()
cnx.close()

3. 輸出到檔案(使用當前日期做檔名)

import time
filename = 'page_list_'+str(time.strftime("%Y%m%d"))+'.txt'
output = open(filename,'w')
output.write(str(page_title).lstrip('(b\'').rstrip('\',)')+"\n")
output.close()

這裡page_title是上面從資料庫中檢索出來的欄位名。因為輸出都是(b'pagename')的格式,所以又做了一些處理,刪除了多餘的字元。

這樣,檢索出的內容就可以直接儲存到以日期為名字的檔案中了。

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對我們的支援。如果你想了解更多相關內容請檢視下面相關連結