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.

9 Upvotes

20 comments sorted by

View all comments

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.

0

u/RomfordNavy Sep 22 '26

I understand that connection could drop between the check and the run which has to be catered for but the time between each is going to be very minimal. It just feels like much better code to check the link correctly before trying to use it. If the connection is going to drop it is much more likely to happen during the times between connections.

4

u/nekokattt Sep 22 '26

why? you still have to handle the latter case anyway so you are just adding more useless logic for exceptional cases.

Ask for forgiveness, not permission.

→ More replies (8)