简体   繁体   中英

How can redirect output of SQL query to a text file using Python

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?

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM