Hoping someone can help me out here to write an efficient code. I am fairly new to python and not the most efficient.
I have a ODBC connection to a SQL database and here is the code for that:
import pyodbc
import pandas as pd
import csv
cnxn = pyodbc.connect("DSN=acc_DB")
cursor = cnxn.cursor()
cursor.execute("select top 10 * from Table_XX")
rows = cursor.fetchall()
Now from here what i get is a this:


Then i put that in a dataframe and out to a csv using this code
DF = pd.DataFrame(rows)
DF.to_csv('out.csv',sep=',')
The problem is:
DF is not recognizing the column names, there is just a value of 0 for columns

How do i put this in the Dataframe in a table format with the column headers and no column types?? Like i would in a SQL query i execute on MS SQL management studio?

If you want the DataFrame to include the column names you can do
crsr = cnxn.cursor()
rows = crsr.execute('select top 10 * from Table_XX').fetchall()
df = pd.DataFrame.from_records(rows, columns=[x[0] for x in crsr.description])
Then to dump the results to CSV with column headings you can do
df.to_csv(r'C:\Users\Gord\Desktop\out.csv', index=False)
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