Should I check a MySQL connection before every query?

0
0
Asked By MellowCedar42 On

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?

4 Answers

Answered By BrightOtter7 On

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.

Answered By QuietMarble_18 On

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.

Answered By CrispWillow9 On

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.

Answered By SilverKite306 On

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.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.