简体   繁体   中英

python close mysql database connection

I have a python script which uses a MySQL database connection, I want the database connection to be closed when the instance of the class does no longer exist therefore in my class I implemented a disconnect method as follows:

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

Now I was thinking of calling this method as follows:

def __del__(self):
    self.disconnect()

However I've read that you cannot assume that the __del__ method will ever be called, if that is the case, what is the correct way? Where / when should I call the disconnect() method?

Important sidenote is that my script is running as a unix daemon and is instantiated as follows:

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

The above takes the class MyDaemon and creates an Unix Daemon by executing a double fork.

Maybe you could use with statment and populate __exit__ method. For example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM