#! 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遊標