SQL with Python:如何在类中提交SQL事务?

2024-10-01 00:26:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我上课的经验有限,所以我很抱歉。我有一个数据库类。我创建了它的一个实例,并尝试通过它运行SQL函数,这些函数可以正常工作,直到我需要用conn.commit()保存一个INSERT到。我的代码是follows:- 你知道吗

Class DatabaseClass():
    def __init__(self):
        self.open_database()

    def open_database(self):
        conn = pyodbc.connect(
                 r"Driver={SQL Server};"
                 r"Server=ServerName;"
                 r"Database=DatabaseName;"
                 r"Trusted_Connection=yes;"
                 )
        self.cursor = conn.cursor()

    def NewRecord()
        self.cursor.execute ("INSERT INTO ....")
        self.conn.commit()

db = DatabaseClass()
db.NewRecord()

但我得到了错误

"DatabaseClass object has no attribute 'conn'".

我该怎么做才能让NewRecord函数知道它处理的是什么连接

谢谢


Tags: 函数self数据库dbsqlserverdef经验