【发布时间】:2020-12-30 20:18:24
【问题描述】:
想知道为什么 Python 使用下面的代码返回 'NoneType' object has no attribute 'connection'。我相信我已经在类中正确创建了 self.connection 变量,但是尝试使用实例调用它会返回上述错误。在我检索到connection 属性之前,连接是否以某种方式终止?
import pyodbc
class sql:
def __init__(self):
self.driver = "{ODBC Driver 17 for SQL Server}"
self.server = ".\SQLEXPRESS"
self.database = "lotto"
self.trusted_connection = "YES"
self.mars_connection = "YES"
def sql_conn(self):
"""Connect to local SQL Server"""
print('\nConnecting to SQL Server...')
self.connection = pyodbc.connect(
'DRIVER=' + self.driver
+ ';SERVER=' + self.server
+ ';DATABASE=' + self.database
+ ';Trusted_Connection=' + self.trusted_connection
+ ';MARS_CONNECTION=' + self.mars_connection
)
print(self.connection)
self.cursor = self.connection.cursor()
print('\nConnection to SQL Server established.')
sql_instance = sql()
conn = sql_instance.sql_conn().connection
【问题讨论】:
标签: python sql pyodbc nonetype