PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

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

巴扎黑
巴扎黑 原创
2016-12-08 10:40:55 1444浏览

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

 

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

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。