Python pyodbc 'execute only'

Python pyodbc 'execute only'

我正在尝试使用 pyodbc 连接到本地 MSSQL 数据库,代码如下:

import pyodbc
conn = pyodbc.connect('Driver={ODBC Driver 17 for SQL Server};'
'Server=localhost;'
'Database=SampleDb;'
'Trusted_Connection=yes;')

cursor = conn.cursor()
cursor.execute = ('SELECT * FROM SampleDb.dbo.flights')

for row in cursor:
    print(row)

出现以下错误:

cursor.execute = ('SELECT * FROM SampleDb.dbo.flights')
AttributeError: 'pyodbc.Cursor' object attribute 'execute' is read-only

cursor.execute 是一个函数,所以你只需要调用它,而不是给它赋值。试试这个:

cursor.execute('SELECT * FROM SampleDb.dbo.flights')

来源: