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?
row_count = count1.fetchval()and you'll have anintvariable namedrow_countthat you can print.