使用Python將Mysql的查詢數(shù)據(jù)導(dǎo)出到文件的方法
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. 輸出到文件(使用當(dāng)前日期做文件名)
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')的格式,所以又做了一些處理,刪除了多余的字符。
這樣,檢索出的內(nèi)容就可以直接保存到以日期為名字的文件中了。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
- mysql實現(xiàn)查詢數(shù)據(jù)并根據(jù)條件更新到另一張表的方法示例
- MySQL Union合并查詢數(shù)據(jù)及表別名、字段別名用法分析
- MYSQL如何自動為查詢數(shù)據(jù)的結(jié)果編上序號詳解
- java實現(xiàn)連接mysql數(shù)據(jù)庫單元測試查詢數(shù)據(jù)的實例代碼
- php基礎(chǔ)之連接mysql數(shù)據(jù)庫和查詢數(shù)據(jù)
- mysql 查詢數(shù)據(jù)庫中的存儲過程與函數(shù)的語句
- MySQL 隨機查詢數(shù)據(jù)與隨機更新數(shù)據(jù)實現(xiàn)代碼
- MySQL按小時查詢數(shù)據(jù),沒有的補0
相關(guān)文章
Python利用memory_profiler實現(xiàn)內(nèi)存分析
memory_profiler是第三方模塊,用于監(jiān)視進程的內(nèi)存消耗以及python程序內(nèi)存消耗的逐行分析。本文將利用memory_profiler實現(xiàn)內(nèi)存分析,需要的可以參考一下2022-10-10
Python實現(xiàn)將內(nèi)容寫入文件的五種方法總結(jié)
本篇帶你詳細(xì)看一下python將內(nèi)容寫入文件的方法以及細(xì)節(jié),主要包括write()方法、writelines()?方法、print()?函數(shù)、使用?csv?模塊、使用?json?模塊,需要的可以參考一下2023-04-04

