简体   繁体   English

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

[英]Read db and write to file in python

I have a connection to mysql db and making queries with that but I need them write to file immediately, what is the easy way of do this ? 我有一个与mysql db的连接并使用它进行查询,但是我需要它们立即写入文件,这样做的简单方法是什么?

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

.. ..

You can use the codes above:(each row inserted as new lines) 您可以使用上面的代码:(每行插入为新行)

 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)

You can do this using the native File writer that comes with Python. 您可以使用Python随附的本机File writer进行此操作。 Below is an example of how you would do that: 以下是如何执行此操作的示例:

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)

TIP: Beware, setting the file mode to W will overwrite the file if it already exists 提示:当心,将文件模式设置为W将覆盖该文件(如果已存在)

TIP: The file path must be relative to your executing python script 提示:文件路径必须相对于您正在执行的python脚本

Resource: https://docs.python.org/2/tutorial/inputoutput.html 资源: https : //docs.python.org/2/tutorial/inputoutput.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM