28

The question says everything. How can I check if my MySQL connection is closed in Python?

I'm using MySQLdb, see http://mysql-python.sourceforge.net/

1 Answer 1

34

The Connection.open field will be 1 if the connection is open and 0 otherwise. So you can say

if conn.open:
    # do something
Sign up to request clarification or add additional context in comments.

4 Comments

as a matter of fact, it does not work for me. even if conn.open is true, it would still throw an exception "The server has gone away" when I try to do the query after a long idle time.
@Walty: The conn.open attribute will tell you whether the connection has been explicitly closed or whether a remote close has been detected. However, it's always possible that you will try to issue a query and suddenly the connection is found to have given out - there is no way to detect this ahead of time (indeed, it might happen during the process of issuing the query), so the only truly safe thing is to wrap your calls in a try/except block.
@EliCourtwright - what is the exception type that is thrown if a 'try' fails from a mysql error?
There can be various exception types, but generally you want to catch a MySQLdb.OperationalError , and if the first item in the error when treated as a tuple (e[0], if you're assigning the error to a new variable 'e') == 2006, that indicates that the connection must be re-connected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.