user4878449
user4878449

Reputation:

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 ?

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

..

Upvotes: 2

Views: 1116

Answers (2)

user4005632
user4005632

Reputation:

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)

Upvotes: 1

Stephen Rodriguez
Stephen Rodriguez

Reputation: 1037

You can do this using the native File writer that comes with Python. 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

TIP: The file path must be relative to your executing python script

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

Upvotes: 1

Related Questions