python - weakly-referenced object no longer exists? 数据库连接关闭问题
PHP中文网
PHP中文网 2017-04-18 10:23:32
0
2
1433
#! 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上的方案就是我写的这样,但是还是有问题,难道是我的翻译软件有问题?

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(2)
伊谢尔伦

Okay, answer it yourself. I don’t know what caused the error. I’ll answer it later when my level is higher. Temporary solution:

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()

Supplement:
It turns out that you cannot close the cursor in __del__()

刘奇

It may be that your configuration is wrong and you are not connected to mysql
If this code self.cur = self.conn.cursor() reports an error, it means you are not connected

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template