【发布时间】:2011-01-29 17:38:50
【问题描述】:
我想使用 python 脚本将 mysql 数据库表内容转换为 Excel(.xls) 或逗号分隔文件(csv)...可以吗?谁能帮帮我?
提前致谢, 尼米
【问题讨论】:
标签: python mysql file csv xlwt
我想使用 python 脚本将 mysql 数据库表内容转换为 Excel(.xls) 或逗号分隔文件(csv)...可以吗?谁能帮帮我?
提前致谢, 尼米
【问题讨论】:
标签: python mysql file csv xlwt
安装第三方项目mysqldb 后,您可以轻松读取该表,例如:
import MySQLdb
conn = MySQLdb.connect (host = "localhost",
user = "testuser",
passwd = "testpass",
db = "test")
cursor = conn.cursor()
cursor.execute("SELECT * FROM thetable")
while True:
row = cursor.fetchone()
if row is None: break
# here: do something with the row
您当然可以使用 Python 的标准库 csv 模块将每一行写入一个 csv 文件——您只需要在代码开头添加一个 import csv。然后,在cursor.execute之后,可以使用如下代码:
with open('thefile.csv', 'w') as f:
writer = csv.writer(f)
while True:
row = cursor.fetchone()
if row is None: break
writer.writerow(row)
如果您想写入.xls 文件而不是.csv,请参阅第三方模块xlwt。
【讨论】: