gpt4 book ai didi

python - 如何使用 pyodbc 从 SQL 查询返回列表?

转载 作者:太空狗 更新时间:2023-10-30 00:04:40 33 4
gpt4 key购买 nike

我正在尝试运行选择查询以在 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

我希望看到类似下面的内容(即我的 SQL 表)

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

列表不是使用 pyodbc 从 SQL 查询返回数据的最佳方式吗?

代码

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())

最佳答案

如果您想将查询结果作为列表的列表返回,并将您的列名作为第一个子列表(类似于您问题中的示例输出),那么您可以执行以下操作:

import 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']

根据您使用结果的方式,我经常发现拥有一个字典列表更有用。例如:

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'}

关于python - 如何使用 pyodbc 从 SQL 查询返回列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53085607/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com