1

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.

5
  • "I am getting errors when I try to execute my SQL statement" You forgot to include said errors. Commented Sep 17, 2020 at 17:09
  • I have just updated this Commented Sep 17, 2020 at 17:09
  • 1
    shouldn't you be using cursor.fetchAll() Commented Sep 17, 2020 at 17:10
  • 1
    like here: stackoverflow.com/questions/63942179/… Commented Sep 17, 2020 at 17:10
  • Let me try this now and see, thank you Commented Sep 17, 2020 at 17:11

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

3 Comments

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() ?
it should, you were just missing the fetchall() before you started looping thru the rows. You still need to call the read function
Oh wow it works, thank you so much for your knowledge

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.