1

I am trying to learn how to get Microsoft SQL query results using python and pyodbc module and have run into an issue in returning the same results using the same query that I use in Microsoft SQL Management Studio.

I've looked at the pyodbc documentation and set up my connection correctly... at least I'm not getting any connection errors at execution. The only issue seems to be returning the table data

import pyodbc
import sys
import csv

cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=<server>;DATABASE=<db>;UID=<uid>;PWD=<PWD>')

cursor = cnxn.cursor()

cursor.execute("""
                SELECT request_id

                From audit_request request

                where request.reception_datetime between '2019-08-18' and '2019-08-19' """)

rows = cursor.fetchall()

for row in cursor:
    print(row.request_id)


When I run the above code i get this in the python terminal window:

Process returned 0 (0x0)        execution time : 0.331 s
Press any key to continue . . .

I tried this same query in SQL Management Studio and it returns the results I am looking for. There must be something I'm missing as far as displaying the results using python.

3
  • Can you do a simple SELECT GETDATE() and get results back? Figuring this out will help us figure out if the problem is in your data, or your connection to the database. Commented Aug 27, 2019 at 17:50
  • Same results with SELECT GETDATE() Commented Aug 27, 2019 at 17:53
  • @NeerajAgarwal might have the answer, for row in rows, not in cursor. Let us know if that works. Commented Aug 27, 2019 at 17:53

1 Answer 1

1

You're not actually setting your cursor up to be used. You should have something like this before executing:

cursor = cnxn.cursor()

Learn more here: https://github.com/mkleehammer/pyodbc/wiki/Connection#cursor

Sign up to request clarification or add additional context in comments.

4 Comments

I actually do have that. I missed it while I was pasting everything into this thread. I'll update my post.
You should have for row in rows instead of for row in cursor.
Nice catch, @NeerajAgarwal. Add as an answer!
@NeerajAgarwal That's it! Thanks.

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.