I have connected SQL Server with Python using pyodbc module. The script seems to have run correctly, however, I am getting errors when I try to execute my SQL statement.
This is what I have done:
import pandas
import numpy
import pyodbc
conn = pyodbc.connect(
'Driver={SQL Server};'
'Server=test\SQLEXPRESS;'
'Database=test1;'
'Trusted_Connection=yes;'
)
cursor = conn.cursor()
def read(conn):
print("Read")
cursor = conn.cursor()
cursor.execute("select * from table")
for row in cursor:
print(f'row = {row}')
print()
read(conn) #to execute
I am wanting to execute a query that I would normally run within my SQL Server, but in Python:
SELECT * FROM table
This is the error:
ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC SQL Server Driver][SQL
Server]Invalid object name 'Node'. (208) (SQLExecDirectW)")
I am actively researching this.
asked Sep 17, 2020 at 17:07
Lynn
4,4286 gold badges35 silver badges67 bronze badges
1 Answer 1
Try this:
def read(conn):
print("Read")
cursor = conn.cursor()
cursor.execute("select * from table")
allrows = cursor.fetchall()
for row in allrows:
print(f'row = {row}')
print()
answered Sep 17, 2020 at 17:15
E.J. Brennan
46.9k8 gold badges94 silver badges120 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Lynn
Thank you, I didn't get that error that I had before, so I believe this works. The kernel is running now. By executing this code, it should give me the query output right? - Or must I 'call' the function? read() ?
E.J. Brennan
it should, you were just missing the fetchall() before you started looping thru the rows. You still need to call the read function
Lynn
Oh wow it works, thank you so much for your knowledge
default
cursor.fetchAll()