2

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")

..

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.