首页 > 编程 > Python > 正文

使用Python将Mysql的查询数据导出到文件的方法

2019-11-25 13:13:07
字体:
来源:转载
供稿:网友

mysql官方提供了很多种connector,其中包括python的connector。

下载地址在:http://dev.mysql.com/downloads/connector/python/ 

直接安装即可。

在python中:

1. 连接:

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

2. 查询:

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

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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对武林网的支持。如果你想了解更多相关内容请查看下面相关链接

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表