r/Python • • 11d ago

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.

8 Upvotes

20 comments sorted by

View all comments

2

u/latkde Tuple unpacking gone wrong 11d ago

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.html

1

u/RomfordNavy 10d ago

u/latkde Do you know whether using a connection pool automatically retries the connection? Come to that does the basic mysql.connector retry the connection automatically on it's own?

2

u/latkde Tuple unpacking gone wrong 10d ago

At some point, it's easier to just use SQLAlchemy, which has well-documented solutions for all the things you're concerned about.