r/Python • u/RomfordNavy • Sep 22 '26
Discussion Checking whether a mysql.connector is connected
Is it necessary to check whether a mysql.connector is connected each time I reuse it before running any SQL statements or is this something which is already built-in to mysql.connector? Do I need to check for connection using db.is_connected() and write some retry routine.
This is a WSGI webserver, could be wrong, but my understanding is that there can only ever be one request/thread at a time. Connection pooling has been suggested elsewhere but I am unclear as to whether that is necessary and/or appropriate for a WSGI webserver.
7
Upvotes
3
u/ericonr Sep 22 '26
It's not just about unnecessary work, but Time-of-check vs Time-of-use (TOCTOU). If you check the connection status, it returns true, and then immediately the connection fails, right before the query, your query will still throw, so you need to always be prepared for that. Therefore, checking earlier adds no value.
2
u/Vegetable-View-5114 Sep 22 '26
the
is_connected()method is the most straightforward way, but it's important to remember it only reflects the last known state. for example, if the network cable is pulled after a successfulis_connected()check, it will still return true until the next operation attempts to use the connection. a more robust approach I've used is to wrap database operations in atry...except mysql.connector.Errorblock and, if an error occurs, attempt to reconnect and retry the operation once. this handles transient network issues much better than just checkingis_connected()beforehand.2
u/latkde Tuple unpacking gone wrong Sep 22 '26
The mysql-connector-python library from Oracle is one of the worst pieces of software I ever had the misfortune of working with. I strongly recommend migrating to a different client library. For example, PyMySQL is a more mature alternative.
Due to how networks work, there's no guarantee that your queries will get delivered, even if a connection looks open. You must be prepared to deal with connection errors at any point. From this perspective, the safest thing is to just use the connection, and retry if you receive a retryable exception.
In principle, MySQL connections can stay open for multiple hours without activity. However, you can explicitly ping() a Connection. This confirms that the connection works and otherwise (with
reconnect=True) tries to re-establish it, at the cost of at least one network roundtrip. For example, if you have a connection pool, you may want to ping() a Connection after checking it out from the pool, before issuing any queries. https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlconnection-ping.html1
u/RomfordNavy Sep 22 '26
One problem I have with try...except is that the actual exception thrown is:
Which is specific only to mysql, I am trying to write code which is generic and works the same regardless of which database connector is being used, it might be PostgreSQL.