Yes, closing the connection in the __del__()
method is very dubious. When and if that method is called is the decision of the garbage collector. It may never get called, or may not get called until well after you have established another connection to the database.
You must call the close()
method yourself. I generally do this by adding a close()
method to my connection-wrapping class and ensuring that it gets called using try / finally
.
I have found it necessary in at least one application to make certain that I call close()
in addition to commit()
or rollback()
when I'm done with a connection.