使用Python执行存储过程时,如何保留列标题?
运行下面显示的代码后,我从存储过程中收到所有数据。但是,未返回列名:
import pandas as pd
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
'Server=PMI0317\Prod;'
'Database=Warehouse;'
'Trusted_Connection=yes;'
)
cursor = conn.cursor()
cursor.execute('SET NOCOUNT ON;EXEC Test.storedproc')
results = cursor.fetchall()
df = pd.DataFrame.from_records(results)
df
输出[113]:
0 1 2 3 4 5 ... 15 16 17 18 19 20
0 9593746 0 COOKCHILDRENS.ORG 1 1.0 Dog ... 0 0 0 0 0 2
1 9593723 0 gmail.com 1 1.0 Dog ... 0 0 12 16 0 0
list(df.columns)
Out[114]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
如您所见,它返回我的数据,但列名称为数字。为什么会发生这种情况?我需要更改结果功能以保留原始列名称?
After I run my code shown below, I receive all the data from my stored procedure. However, the column names are not returned:
import pandas as pd
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
'Server=PMI0317\Prod;'
'Database=Warehouse;'
'Trusted_Connection=yes;'
)
cursor = conn.cursor()
cursor.execute('SET NOCOUNT ON;EXEC Test.storedproc')
results = cursor.fetchall()
df = pd.DataFrame.from_records(results)
df
Output[113]:
0 1 2 3 4 5 ... 15 16 17 18 19 20
0 9593746 0 COOKCHILDRENS.ORG 1 1.0 Dog ... 0 0 0 0 0 2
1 9593723 0 gmail.com 1 1.0 Dog ... 0 0 12 16 0 0
list(df.columns)
Out[114]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
As you see, it returns my data but column names are changes to numeric. why does this happen? What do I need to change in results function to retain original column names?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以从光标描述中添加列名:
或者,您可以使用
read_sql
并直接加载到pandas:you can add the column name from cursor description:
alternatively, you could use
read_sql
and directly load into pandas :