Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3: Does mysql db connection need to be explicitly closed in function?

Do you have to close mysql (pymysql) connection explicitly within a function in python3, or can you let python3 take care of it automatically as it gets out of scope.

like image 901
Paul Grant Avatar asked Oct 14 '25 10:10

Paul Grant


1 Answers

If an object goes out of scope, it doesn't mean Python will call .close() on it. pymysql does do some cleanup (closing the socket) in the __del__ method of a connection object (source) but I wouldn't rely on it - in particular because it only closes the socket and doesn't communicate to MySQL that the connection is being closed (which is what .close() does).

As such it's better to be explicit and close the connection yourself. This also means you know exactly when the connection is closed.

like image 140
Simeon Visser Avatar answered Oct 17 '25 05:10

Simeon Visser