Python 3-使用MySQL连接器时光标上的参考错误弱

难以理解一些基本的Python 3代码出了什么问题。它是一个使用MySQL连接器的数据库类,该类随后又在另一个类中继承。

数据库类(database.py):

import mysql.connector

config = {
    'host': 'localhost','user': '...','password': '...','database': '...'
}

class Database:

    def __init__(self):
        self.connect()

    def connect(self):
        try:
            db = mysql.connector.connect(**config)
            self.cursor = db.cursor()
        except mysql.connector.Error as err:
            print(err.msg)
            return False

继承数据库类的类:

import mysql.connector
import datetime
from database import Database

class Logger(Database):

    def __init__(self):
        super().__init__()

    def get_row(self,id):
        try:
            sql = ("SELECT * FROM logs WHERE id = %s")
            self.cursor.execute(sql,(id,))
            result = cursor.fetchone()
            return result
        except mysql.connector.Error as err:
            print(err.msg)
            return False

还有调用代码...

obj = Logger()
data = obj.get_row(2)

弱参考错误(在光标上):

Traceback (most recent call last):
  File "examples.py",line 71,in <module>
   data = obj.get_row(2)
 File "examples.py",line 28,in get_row
   self.cursor.execute(sql,))
ReferenceError: weakly-referenced object no longer exists

我在这里不了解什么?我知道该错误特定于MySQL连接器的使用,因为我已经知道它使用了弱引用。我只是对如何在继承的类方法中正确地重用/维护对父类的 cursor 属性的引用感到困惑。预先感谢!

iCMS 回答:Python 3-使用MySQL连接器时光标上的参考错误弱

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/2109007.html

大家都在问