使用python將mysql的查詢資料匯出到檔案

來源:互聯網
上載者:User
在python中:

1. 串連:

Python代碼

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

2. 查詢:

Python代碼

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, last_name, hire_date) in cursor:    print("{}, {} was hired on {:%d %b %Y}".format(      last_name, first_name, hire_date))  cursor.close()  cnx.close()

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

Python代碼

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')的格式,所以又做了一些處理,刪除了多餘的字元。

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

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.