Heim  >  Fragen und Antworten  >  Hauptteil

#->Ausnahmefehler: Das schwache Referenzobjekt existiert nicht mehr

Dies ist der Code, der den Fehler erzeugt:

import mysql.connector
import datetime

class Command:
    def __init__(self):
        mydb = mysql.connector.connect(host='localhost', passwd='1234', user='root', database='customers')

        self.mycursor = mydb.cursor()

    def execute(self, contest_id, url, Questions):
        date = datetime.date.today()
        Time = datetime.datetime.now().strftime("%I:%M")

        self.mycursor.execute(f"INSERT INTO contest(contest_name, url_tag, Questions, At_date, At_time) VALUES('{contest_id}', '{url}', {Questions}, '{date}', '{Time}')")

Ich führe Python-Code aus, erhalte jedoch die folgende Fehlermeldung:

Traceback (most recent call last):
    
   File "C:\python39\lib\site-packages\mysql\connector\cursor.py", line 518, in execute
    if not self._connection:
ReferenceError: weakly-referenced object no longer exists

P粉070918777P粉070918777207 Tage vor358

Antworte allen(2)Ich werde antworten

  • P粉329425839

    P粉3294258392024-03-27 10:03:31

    我的猜测是您的连接丢失了,因为它不属于您的班级。你能尝试一下这个方法吗?

    import mysql.connector
    import datetime
    
    class Command:
        def __init__(self):
            self.conn = mysql.connector.connect(host='localhost', passwd='1234', user='root', database='customers')
    
            self.mycursor = self.conn.cursor()
    
        def execute(self, contest_id, url, Questions):
            date = datetime.date.today()
            Time = datetime.datetime.now().strftime("%I:%M")
    
            self.mycursor.execute(f"INSERT INTO contest(contest_name, url_tag, Questions, At_date, At_time) VALUES('{contest_id}', '{url}', {Questions}, '{date}', '{Time}')")

    Antwort
    0
  • 大鹏

    大鹏2024-03-27 11:06:29

    在你的代码中,mydb 数据库连接对象是在 Command 类的 __init__ 方法中创建的。然而,这个连接对象并没有作为类的属性保存下来,因此当 __init__ 方法执行完毕后,mydb 对象就可能会被 Python 的垃圾回收器回收,因为它不再被任何变量引用。

    为了解决这个问题,你需要将数据库连接对象 mydb 保存为类的一个属性,这样它就不会在 __init__ 方法执行完毕后被回收了。你可以通过在 self 上设置一个属性来实现这一点,比如 self.mydb。

    import mysql.connector  
    import datetime  
      
    class Command:  
        def __init__(self):  
            self.mydb = mysql.connector.connect(host='localhost', passwd='1234', user='root', database='customers')  
            self.mycursor = self.mydb.cursor()  
      
        def execute(self, contest_id, url, questions):  
            date = datetime.date.today()  
            time = datetime.datetime.now().strftime("%H:%M")  # 使用 24 小时制可能更为普遍  
      
            # 使用参数化查询以防止 SQL 注入攻击  
            query = "INSERT INTO contest (contest_name, url_tag, Questions, At_date, At_time) VALUES (%s, %s, %s, %s, %s)"  
            values = (contest_id, url, questions, date, time)  
              
            try:  
                self.mycursor.execute(query, values)  
                self.mydb.commit()  # 提交事务以确保数据被保存到数据库  
            except mysql.connector.Error as err:  
                print(f"Error: {err}")  
                self.mydb.rollback()  # 回滚事务以防止部分数据写入

    Antwort
    0
  • StornierenAntwort