Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a list from SQL query using pyodbc?

I am trying to run a select query to retrieve data from SQL Server using pyodbc in python 2.7. I want the data to be returned in a list. The code I have written is below.

It works, kinda, but not in the way I expected. My returned list looks something like below:

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

I was hoping to see something like below (i.e. my table in 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

Is a list not the best way to return data from a SQL query using pyodbc?

Code

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())
like image 944
mHelpMe Avatar asked Oct 31 '18 14:10

mHelpMe


People also ask

How to connect Python to SQL Server using pyodbc?

Steps to Connect Python to SQL Server using pyodbc 1 Install pyodbc. ... 2 Retrieve the server na ... 3 Obtain the database na ... 4 Get the table name. ... 5 Connect Python to SQL ...

Does pyodbc follow the Python DB API for cursor names?

If you look at the documentation about pyodbc cursor objects, you'll find that each row has a set of attributes that correspond in name to the column names from your table. While I have no database to test, I have a slight feeling that pyodbc doesn't actually follow the Python DB API 2.0 fully, and that a single row is not a list of its columns.

How do I use Python with SQL Server?

Once you established such a connection between Python and SQL Server, you can start using SQL in Python to manage your data. You can also use Python to insert values into SQL Server table . For further information about the pyodbc package, please visit the pyodbc documentation .

Where can I find more information about the pyodbc package?

For further information about the pyodbc package, please visit the pyodbc documentation.


1 Answers

If you want to return your query results as a list of lists with your column names as the first sublist (similar to the example output in your question), then you can do something like the following:

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

Depending on how you are using the results, I often find it more useful to a have a list of dicts. For example:

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'}
like image 198
benvc Avatar answered Sep 29 '22 20:09

benvc