简体   繁体   中英

Exporting data from SQL server to Excel using python pyodbc and pandas Data frame

I am new to Stack overflow as well as Python. Below is my program and I am trying to learn how to export data from SQL server to excel using python program. I know ways to directly exporting from SQL server, this is I am just trying to learn. Program below does not give any errors but it does just gives column headers but not actual data.

import pyodbc
import pandas as pd

cnxn = pyodbc.connect("Driver={SQL Server};SERVER=hostname;Database=Practice;UID=XXX;PWD=XXX")

cursor = cnxn.cursor()
cursor.execute('SELECT * FROM insurance')

columns = [desc[0] for desc in cursor.description]
data = cursor.fetchall()
df = pd.DataFrame([tuple(t) for t in cursor.fetchall()], columns=columns)

writer = pd.ExcelWriter('foo.xlsx')
df.to_excel(writer, sheet_name='bar')
writer.save()

easier than that!

import pyodbc
import pandas as pd

cnxn = pyodbc.connect("Driver={SQL Server};SERVER=xxx;Database=xxx;UID=xxx;PWD=xxx")

pd.read_sql('SELECT * FROM insurance',cnxn).to_excel('foo.xlsx')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM