return column names from pyodbc execute() statement

后端 未结 4 995
感情败类
感情败类 2020-12-08 02:05
from pandas import DataFrame
import pyodbc

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


        
相关标签:
4条回答
  • 2020-12-08 02:50

    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)
    
    0 讨论(0)
  • 2020-12-08 02:56

    You can get the columns from the cursor description:

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

    0 讨论(0)
  • 2020-12-08 03:02

    Improving on the previous answer, in the context of pandas, I found this does exactly what I expect:

    DF.columns = DataFrame(np.matrix(cursor.description))[0]
    
    0 讨论(0)
  • 2020-12-08 03:03

    In case you are experiencing the NoneType error from the code provided by Matti John, make sure to make the cursor.description call after you have retrieved data from the database. An example:

    cursor = cnxn.cursor()
    cursor.execute("SELECT * FROM my_table")
    columns = [column[0] for column in cursor.description]
    

    This fixed it for me.

    0 讨论(0)
提交回复
热议问题