我试图运行一个选择查询以使用python 2.7中的pyodbc从sql Server检索数据.我希望数据在列表中返回.我写的代码如下.
它有点工作,但不符合我的预期.我的返回列表如下所示:
Index Type Size Value
0 Row 1 Row object of pyodbc module
1 Row 1 Row object of pyodbc module
...
105 Row 1 Row object of pyodbc module
ActionId AnnDate Name SaleValue
128929 2018-01-01 Bob 105.3
193329 2018-04-05 Bob 1006.98
...
23654 2018-11-21 Bob 103.32
码
import pyodbc
def GetsqlData(dbName,query):
sPass = 'MyPassword'
sServer = 'MyServer\\sql1'
uname = 'MyUser'
cnxn = pyodbc.connect("Driver={sql Server Native Client 11.0};"
"Server=" + sServer + ";"
"Database=" + dbName + ";"
"uid=" + uname + ";pwd=" + sPass)
cursor = cnxn.cursor()
cursor.execute(query)
return list(cursor.fetchall())
最佳答案
如果要将查询结果作为列表列表返回,并将列名称作为第一个子列表(类似于问题中的示例输出),则可以执行以下操作:
原文链接:https://www.f2er.com/python/438929.htmlimport pyodbc
cnxn = pyodbc.connect("YOUR_CONNECTION_STRING")
cursor = cnxn.cursor()
cursor.execute("YOUR_QUERY")
columns = [column[0] for column in cursor.description]
results = [columns] + [row for row in cursor.fetchall()]
for result in results:
print result
# EXAMPLE OUTPUT
# ['col1','col2']
# ['r1c1','r1c2']
# ['r2c1','r2c2']
根据您使用结果的方式,我经常发现有一个dicts列表更有用.例如:
results = [dict(zip(columns,row)) for row in cursor.fetchall()]
for result in results:
print result
# EXAMPLE OUTPUT
# {'col1': 'r1c1','col2':'r1c2'}
# {'col1': 'r2c1','col2':'r2c2'}