pyodbc: query results to CSV?

↘锁芯ラ 提交于 2019-12-06 11:05:58

问题


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

回答1:


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"



回答2:


Another method is to use the pandas module. Very useful when using tables. Pandas has lots of other useful data management features.

import pandas as pd
import pyodbc

conn = pyodbc.connect("DSN=myDb")
crsr = conn.cursor()
crsr.execute(""" #COMMAND GOES HERE """)
rows = crsr.fetchall()
SQLdata = pd.DataFrame(columns=["COLUMN","DATA"]) #naming your columns is optional, but useful
SQLdata["COLUMN"] = [i[0] for i in rows]
SQLdata["DATA"] = [i[1] for i in rows]
SQLdata.to_csv("myCsv.csv")



回答3:


Improving billmanH's answer:

conn = pyodbc.connect(' ... ')
cursor = conn.cursor()

cursor.execute('SELECT ...')

col_headers = [ i[0] for i in cursor.description ]
rows = [ list(i) for i in cursor.fetchall()] 
df = pd.DataFrame(rows, columns=col_headers)

df.to_csv("test.csv", index=False)


来源:https://stackoverflow.com/questions/42844895/pyodbc-query-results-to-csv

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!