python关闭mysql数据库连接

2 投票
1 回答
1042 浏览
提问于 2025-04-18 01:51

我有一个用Python写的脚本,它连接了一个MySQL数据库。我希望当这个类的实例不再存在时,数据库连接能够自动关闭。因此,我在我的类里实现了一个断开连接的方法,代码如下:

def disconnect(self):
    '''Disconnect from the MySQL server'''
    if self.conn is not None:
        self.log.info('Closing connection')
        self.conn.close()
        self.conn = None
        self.curs = None

现在我在考虑这样调用这个方法:

def __del__(self):
    self.disconnect()

不过我听说不能指望__del__这个方法一定会被调用。如果真是这样,那正确的做法是什么呢?我应该在哪里/什么时候调用disconnect()方法呢?

需要特别说明的是,我的脚本是作为一个Unix守护进程运行的,实例化的方式如下:

if __name__ == '__main__':
    daemon = MyDaemon(PIDFILE)
    daemonizer.daemonizerCLI(daemon, 'mydaemon', sys.argv[0], sys.argv[1], PIDFILE)

上面的代码是通过执行双重分叉来创建一个Unix守护进程,使用的是MyDaemon这个类。

1 个回答

2

也许你可以使用 with 语句,并填充 __exit__ 方法。比如说:

class Foo(object):

  def disconnect(self):
    '''Disconnect from the MySQL server'''
    if self.conn is not None:
        self.log.info('Closing connection')
        self.conn.close()
        self.conn = None
        self.curs = None
        print "disconnect..."

  def __exit__(self, *err):
    self.disconnect()

if __name__ == '__main__':
  with Foo() as foo:
    print foo, foo.curs

撰写回答