Should I check a MySQL connection before every query?

September 21, 2026 4 answers
Asked by MellowCedar42
When reusing a mysql.connector connection in a WSGI web application, should I call db.is_connected() before every SQL statement, or does the connector handle dropped connections automatically? If the connection fails, should I catch the error and reconnect, possibly retrying the operation? Also, is a connection pool necessary, especially if the WSGI server handles only one request or thread at a time?

Answers

SilverKite306
Don't assume a WSGI application always has only one request or thread. That depends on the server configuration and deployment, and multiple worker processes or threads may handle requests concurrently. A single shared connection can cause problems in that situation. Use a connection per request or a connection pool sized for the application's concurrency, and return or close the connection afterward.

NimblePanda55: If the deployment truly has one worker and one request at a time, a pool may be unnecessary, but the code should still cope with a connection going stale between requests.

Reply to this answer
CrispWillow9
If you want database-independent code, put the retry and reconnect policy behind your own database abstraction instead of checking for a connector-specific type throughout the application. Each backend can translate its driver exceptions into a common application-level error. Also, avoid a blanket retry for every exception: syntax errors, constraint violations, and other permanent failures should be reported rather than retried.
Reply to this answer
QuietMarble_18
is_connected() is useful as a quick indication of the last known state, but it isn't an active health check. It won't necessarily notice a network failure until another operation uses the connection. A common pattern is to catch the database driver's exception, reconnect once, and retry only operations that are safe to repeat.
Reply to this answer
BrightOtter7
You generally don't need to check is_connected() before every query. The status can change immediately after the check, so it can't guarantee that the following statement will succeed. Execute the query and handle the connector's exception if the connection has failed. Reconnect when appropriate, but be careful about automatically retrying writes because the server may have processed the statement before the connection dropped.
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions