Mathnode Mathnode - 6 months ago 29
SQL Question

Using python to write mysql query to csv, need to show field names

I have the following:

import MySQLdb as dbapi
import sys
import csv

dbServer='localhost'
dbPass='supersecretpassword'
dbSchema='dbTest'
dbUser='root'

dbQuery='SELECT * FROM pbTest.Orders;'

db=dbapi.connect(host=dbServer,user=dbUser,passwd=dbPass)
cur=db.cursor()
cur.execute(dbQuery)
result=cur.fetchall()

c = csv.writer(open("temp.csv","wb"))
c.writerow(result)


This is produces a garbled mess. I am familiar with using printing record[0] etc. Not sure how I should be going about setting up the formatting. to produce something like what a query would in a console. I cannot do a simple INTO OUTFILE from the mysql server.

Answer

result is a list of rows. So you'll need to iterate through that list and write each row:

for row in result:
    c.writerow(row)
Comments