gpt4 book ai didi

python - 在python中读取数据库并写入文件

转载 作者:行者123 更新时间:2023-11-28 23:57:57 25 4
gpt4 key购买 nike

我连接到 mysql 数据库并使用它进行查询,但我需要它们立即写入文件,执行此操作的简单方法是什么?

conn = MySQLdb.connect(host="localhost",user="root",passwd="",db="mydb")
cursor = conn.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT * FROM books")

..

最佳答案

您可以使用上面的代码:(每行插入为新行)

 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)

关于python - 在python中读取数据库并写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31006455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com