return column names from pyodbc execute() statement

dmvianna picture dmvianna · Oct 3, 2012 · Viewed 49.8k times · Source
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?

Answer

Matti John picture Matti John · Oct 3, 2012

You can get the columns from the cursor description:

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