代码之家  ›  专栏  ›  技术社区  ›  mHelpMe

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

  •  5
  • mHelpMe  · 技术社区  · 6 年前

    我正在尝试运行select查询以使用从SQL Server检索数据 pyodbc 在Python2.7中。我希望数据以列表的形式返回。我写的代码如下。

    有点像,但不是我想象的那样。我返回的列表如下所示:

    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
    

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

    代码

    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 回复  |  直到 6 年前
        1
  •  6
  •   benvc    6 年前

    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'}
    
        2
  •  5
  •   m33n    6 年前

    还有比单子更好的选择,试试看 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 
    

    但我强烈建议你开始和熊猫合作