我正在使用pyodbc访问数据库并打印查询结果。
如何使用pyodbc将整个查询结果(包括列)打印到csv文件?
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()
答案 0 :(得分:9)
如何使用pyodbc将整个查询结果(包括列)打印到csv文件?
您不使用pyodbc“打印”任何内容,但您可以使用csv module将pyodbc查询的结果转储为CSV。
作为一个最小的例子,这对我有用:
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)
生成包含
的CSV文件id,astronaut
1,John Glenn
2,"Edwin ""Buzz"" Aldrin"
答案 1 :(得分:1)
另一种方法是使用pandas模块。使用表时非常有用。 Pandas还有许多其他有用的数据管理功能。
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")
答案 2 :(得分:1)
改善billmanH的答案:
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)
答案 3 :(得分:0)
您可以将选择的结果导出到CSV文件中。
import pandas as pd
import pyodbc
conn = pyodbc.connect('""" Connection String """')
df = pd.read_sql_query('""" Select Query """', conn)
df.to_csv('""" CSV file path """', index=False)