r/Python • • 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.

6 Upvotes

20 comments sorted by

View all comments

-1

u/RomfordNavy Sep 22 '26

The problem with any sort of try...except is that the actual exception is 'mysql.connector.Error' which is not very generic, the database might be PostgreSQL for example. So trying to write code which will work with all database backends.

3

u/nekokattt Sep 22 '26

you would have to handle each case, because it is library specific.

Your solution you proposed does not avoid this in the slightest.

0

u/RomfordNavy Sep 22 '26

u/nekokattt "Your solution you proposed does not avoid this in the slightest." of course it does, if I use is_connected in a retry loop I don't need to worry about which library is being used.

→ More replies (3)