如何使用 Python 将 SQL 查询的输出重定向到文本文件

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

使用 Python 和 pyodbc 模块将 SQL 查询输出重定向到文本文件。

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

但是失败并出现错误:

Type error: Nonetype object is not subscriptable

有人可以帮我将 SQL 查询输出重定向到文件吗?

由于您在打印时已经获取了结果,因此无法再次获取相同的结果。 所以你应该将它分配给一个变量:

count = count1.fetchone()[0]

然后随意使用:

print(count)
...
f.write('\n' + 'Mandatory field missing count:'+ str(count))