【发布时间】: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