使用Python將Mysql的查詢數(shù)據(jù)導出到文件的方法
更新時間:2019年02月25日 17:22:21 作者:iteye_6192
今天小編就為大家分享一篇關于使用Python將Mysql的查詢數(shù)據(jù)導出到文件的方法,小編覺得內容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
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, 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. 輸出到文件(使用當前日期做文件名)
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是上面從數(shù)據(jù)庫中檢索出來的字段名。因為輸出都是(b'pagename')的格式,所以又做了一些處理,刪除了多余的字符。
這樣,檢索出的內容就可以直接保存到以日期為名字的文件中了。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內容請查看下面相關鏈接
您可能感興趣的文章:
- mysql實現(xiàn)查詢數(shù)據(jù)并根據(jù)條件更新到另一張表的方法示例
- MySQL Union合并查詢數(shù)據(jù)及表別名、字段別名用法分析
- MYSQL如何自動為查詢數(shù)據(jù)的結果編上序號詳解
- java實現(xiàn)連接mysql數(shù)據(jù)庫單元測試查詢數(shù)據(jù)的實例代碼
- php基礎之連接mysql數(shù)據(jù)庫和查詢數(shù)據(jù)
- mysql 查詢數(shù)據(jù)庫中的存儲過程與函數(shù)的語句
- MySQL 隨機查詢數(shù)據(jù)與隨機更新數(shù)據(jù)實現(xiàn)代碼
- MySQL按小時查詢數(shù)據(jù),沒有的補0
相關文章
Python利用memory_profiler實現(xiàn)內存分析
memory_profiler是第三方模塊,用于監(jiān)視進程的內存消耗以及python程序內存消耗的逐行分析。本文將利用memory_profiler實現(xiàn)內存分析,需要的可以參考一下2022-10-10