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

时间:2018-10-31 14:22:20

标签: python python-2.7 list pyodbc

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

2 个答案:

答案 0 :(得分:3)

还有比列表更好的选择,请尝试Pandas DataFrame! 它有助于处理列名并应用列明智的操作!

import pandas as pd
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)


    df = pd.read_sql(cnxn, query)

    return df  # Pandas Dataframe

编辑:

如果您希望使用列表列表(每行一个列表),则可以通过以下方式获取列表:

df.values.tolist()  # list of lists 

但是我强烈建议您开始使用熊猫

答案 1 :(得分:1)

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

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