0

Redirect SQL query output to a text file using Python and pyodbc module.

import pyodbc
import os
import sys
conn = pyodbc.connect('Driver={SQL Server};'
                      'Server=win-intrst-srv;'
                      'Database=Interests_db;'
                      'Trusted_Connection=yes;')

cursor = conn.cursor()
count1 = cursor.execute("select count(*) from MissedEvents  where  TenantId > 10000 and remarks like 'Mandatory%' AND RowCreatedDate >= dateadd(hh, -2, getdate())")
print(count1.fetchone()[0]) # This prints out no of rows updated in last 1 hour.

f = open('c:\MonitoringStats\staticentry.txt','a')
f.write('\n' + 'Mandatory field missing count:'+ count1.fetchone()[0])
file.close()

But it's failing with the error:

Type error: Nonetype object is not subscriptable

Can someone help me in redirecting the SQL query output to a file?

2
  • 1
    It seems likely that your query only returns one row. Therefore, calling fetchone() twice could be the problem. Commented Feb 27, 2020 at 17:28
  • Since you are only retrieving a single (scalar) value, just use row_count = count1.fetchval() and you'll have an int variable named row_count that you can print. Commented Feb 27, 2020 at 20:41

1 Answer 1

1

As you already fetch your result when you print it, you cannot fetch that same result again. So you should assign it to a variable :

count = count1.fetchone()[0]

Then use it as you want:

print(count)
...
f.write('\n' + 'Mandatory field missing count:'+ str(count))
Sign up to request clarification or add additional context in comments.

1 Comment

pyodbc's .fetchval() is a handy alternative to .fetchone()[0].

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.