Retrieving Data from SQL Using pyodbc Retrieving Data from SQL Using pyodbc python python

Retrieving Data from SQL Using pyodbc


You are so close!

import pyodbccnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=SQLSRV01;DATABASE=DATABASE;UID=USER;PWD=PASSWORD')cursor = cnxn.cursor()cursor.execute("SELECT WORK_ORDER.TYPE,WORK_ORDER.STATUS, WORK_ORDER.BASE_ID, WORK_ORDER.LOT_ID FROM WORK_ORDER")for row in cursor.fetchall():    print row

(the "columns()" function collects meta-data about the columns in the named table, as opposed to the actual data).


In order to receive actual data stored in the table, you should use one of fetch...() functions or use the cursor as an iterator (i.e. "for row in cursor"...). This is described in the documentation:

cursor.execute("select user_id, user_name from users where user_id < 100")rows = cursor.fetchall()for row in rows:    print row.user_id, row.user_name


you could try using Pandas to retrieve information and get it as dataframe

import pyodbc as cnnimport pandas as pdcnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=SQLSRV01;DATABASE=DATABASE;UID=USER;PWD=PASSWORD')# Copy to Clipboard for paste in Excel sheetdef copia (argumento):    df=pd.DataFrame(argumento)    df.to_clipboard(index=False,header=True)tableResult = pd.read_sql("SELECT * FROM YOURTABLE", cnxn) # Copy to Clipboardcopia(tableResult)# Or create a Excel file with the resultsdf=pd.DataFrame(tableResult)df.to_excel("FileExample.xlsx",sheet_name='Results')

I hope this helps!Cheers!