Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pyodbc: query results to CSV?

Tags:

python

pyodbc

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()
like image 476
Techno04335 Avatar asked Nov 30 '22 09:11

Techno04335


1 Answers

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"
like image 63
Gord Thompson Avatar answered Dec 05 '22 04:12

Gord Thompson