我有一个与mysql db的连接并使用它进行查询但是我需要它们立即写入文件,这样做的简单方法是什么?
conn = MySQLdb.connect(host="localhost",user="root",passwd="",db="mydb")
cursor = conn.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT * FROM books")
...
答案 0 :(得分:1)
您可以使用上面的代码:(每行插入新行)
conn = MySQLdb.connect(host="localhost",user="root",passwd="",db="mydb")
cursor = conn.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT * FROM books")
result_set = cursor.fetchall()
field_names = [val[0] for val in cursor.description]
with open('yourfile.txt', 'a') as f:
for row in result_set:
line = ','.join(row[field_name] for field_name in field_names)
f.write(line)
答案 1 :(得分:0)
您可以使用Python附带的本机File writer执行此操作。以下是如何执行此操作的示例:
with open('/path/to/file.txt', 'w') as f:
conn = MySQLdb.connect(host="localhost",user="root",passwd="",db="mydb")
cursor = conn.cursor(MySQLdb.cursors.DictCursor)
result = cursor.execute("SELECT * FROM books")
f.write(result)
提示:注意,将文件模式设置为W将覆盖文件(如果已存在)
提示:文件路径必须与执行的python脚本相关