Python 从 pyodbc execute() 语句返回列名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12704305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:39:28  来源:igfitidea点击:

return column names from pyodbc execute() statement

pythonpandaspyodbc

提问by dmvianna

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

这很好填充我的 Pandas DataFrame。但是我怎么得到

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

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

直接从光标?该信息是否存储在游标中?

采纳答案by Matti John

You can get the columns from the cursor description:

您可以从游标描述中获取列:

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

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

回答by dmvianna

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]

回答by phoenix10k

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

最近的熊猫有更高级别的read_sql功能,可以为您做到这一点

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)

回答by Morten Wehlast

In case you are experiencing the NoneTypeerror from the code provided by Matti John, make sure to make the cursor.descriptioncall afteryou have retrieved data from the database. An example:

如果您遇到NoneType来自Matti John提供的代码的错误,请确保从数据库中检索数据进行cursor.description调用。一个例子:

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

This fixed it for me.

这为我修好了。