【问题标题】:ReferenceError: weakly-referenced object no longer exists, Python3ReferenceError:弱引用对象不再存在,Python3
【发布时间】:2015-09-07 23:19:07
【问题描述】:

我正在 Python 3 中尝试这个简单的代码:

import mysql.connector
class App():
    def __init__(self):
        self.conexion = mysql.connector.connect(user='?',
                                                password='?',
                                                host='?',
                                                db='?')
        self.cursor = self.conexion.cursor()
    def __del__(self):
        self.conexion.close()
        self.cursor.close() # The code works if i remove this line;

myApp = App()

如果我删除 self.cursor.close() 行,则代码适用于 Python 2 和 Python 3。这应该发生吗?

问题是当我尝试在__del__ 中使用self.cursor.close() 时,如果self.cursor.close()__init__ 中,则代码有效,否则,我什至可以创建表。

我遇到的错误是:

Exception ignored in: <bound method MySQL_App.__del__ of <__main__.MySQL_App object at 0x7f6f87f42278>>
Traceback (most recent call last):
File "filename.py", line 22, in __del__
File "/usr/lib/python3.4/site-packages/mysql/connector/cursor.py", line 338, in close
File "/usr/lib/python3.4/site-packages/mysql/connector/cursor.py", line 310, in _have_unread_result
ReferenceError: weakly-referenced object no longer exists

【问题讨论】:

  • 你为什么要定义__del__()?这很不寻常。
  • 我需要在最后关闭连接。我认为最好的方法是使用__del__()__del__ 不是在析构函数等相同情况下使用吗?)
  • 好的,我将 __del__() 更改为 End() 并且由于某种原因它可以正常工作...
  • 经过一番研究,我发现游标是python垃圾收集的,所以没有必要关闭它。

标签: python mysql mysql-python


【解决方案1】:

你做错了。由于您在连接之后创建了光标,因此您需要在连接之前关闭它。

self.cursor.close()
self.conexion.close()

【讨论】:

    猜你喜欢
    • 2016-10-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 2018-08-28
    • 2020-07-19
    • 2010-12-01
    • 2020-12-01
    • 2020-08-22
    相关资源
    最近更新 更多