#! python3
import mysql.connector
class A:
def __init__(self):
self.dbconfig = {....}
self.conn = mysql.connector.connect(**self.dbconfig)
self.cur = self.conn.cursor()
def __del__(self):
self.cur.close()
self.conn.close()
数据库连接也成功了,但是执行完该类后就会报错:
Exception ignored in: <bound method A.__del__ of <__main__.**** object at 0x0000000001151358>>
Traceback (most recent call last):
File "****.py", line *, in __del__
File "*****\Python35\lib\site-packages\mysql\connector\cursor.py", line 344, in close
ReferenceError: weakly-referenced object no longer exists
还请知道什么原因的司机解惑!万分感谢!
按stackoverflow上的方案就是我写的这样,但是还是有问题,难道是我的翻译软件有问题?
伊谢尔伦2017-04-18 10:25:32
好吧,自己答一下。并不知道是什么原因导致的错误,等以后水平高点再来回答。暂时解决办法:
import mysql.connector
class A:
def __init__(self):
self.dbconfig = {...}
try:
self.conn = mysql.connector.connect(**self.dbconfig)
self.cur = self.conn.cursor()
print('mysql conn success!')
except:
print("mysql conn error!")
def __del__(self):
#if self.cur:
# self.cur.close()
if self.conn:
self.conn.close()
if __name__ == '__main__':
a = A()
补充:
事实证明,不能在__del__()里面close游标