当前位置:Gxlcms > Python > 使用python将mysql的查询数据导出到文件

使用python将mysql的查询数据导出到文件

时间:2021-07-01 10:21:17 帮助过:75人阅读

在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')的格式,所以又做了一些处理,删除了多余的字符。

这样,检索出的内容就可以直接保存到以日期为名字的文件中了。

人气教程排行