I am using pyodbc to access a database and print the query results.
How do I use pyodbc to print the whole query result including the columns to a csv file?
CODE:
import pyodbc
cnxn = pyodbc.connect(
#DATA BASE NAME IS HERE, HID FOR PRIVACY )
cursor = cnxn.cursor()
cursor.execute(""" #COMMAND GOES HERE """)
row = cursor.fetchall() #FETCHES ALL ROWS
cnxn.commit()
cnxn.close()
How do I use pyodbc to print the whole query result including the columns to a csv file?
You don't use pyodbc to "print" anything, but you can use the csv module to dump the results of a pyodbc query to CSV.
As a minimal example, this works for me:
import csv
import pyodbc
conn = pyodbc.connect("DSN=myDb")
crsr = conn.cursor()
# test data
sql = """\
SELECT 1 AS id, 'John Glenn' AS astronaut
UNION ALL
SELECT 2 AS id, 'Edwin "Buzz" Aldrin' AS astronaut
"""
rows = crsr.execute(sql)
with open(r'C:\Users\gord\Desktop\astro.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow([x[0] for x in crsr.description]) # column headers
for row in rows:
writer.writerow(row)
producing a CSV file containing
id,astronaut
1,John Glenn
2,"Edwin ""Buzz"" Aldrin"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With