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