return column names from pyodbc execute() statement


from pandas import DataFrame
import pyodbc

cnxn = pyodbc.connect(databasez)
cursor.execute("""SELECT ID, NAME AS Nickname, ADDRESS AS Residence FROM tablez""")
DF = DataFrame(cursor.fetchall())

This is fine to populate my pandas DataFrame. But how do I get

DF.columns = ['ID', 'Nickname', 'Residence']

straight from cursor? Is that information stored in cursor at all?

6/13/2015 8:47:42 AM

Accepted Answer

You can get the columns from the cursor description:

columns = [column[0] for column in cursor.description]

10/3/2012 11:23:18 AM

Recent pandas have a higher level read_sql functions that can do this for you

import pyodbc
import pandas as pd

cnxn = pyodbc.connect(databasez)
DF = pd.read_sql_query("SELECT ID, NAME AS Nickname, ADDRESS AS Residence FROM tablez", cnxn)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow