pyMySQL: How to check if connection is already opened or close

Volatil3 picture Volatil3 · Jun 28, 2017 · Viewed 15.4k times · Source

I am getting the error InterfaceError (0, ''). Is there way in Pymysql library I can check whether connection or cursor is closed. For cursor I am already using context manager like that:

with db_connection.cursor() as cursor:
  ....

Answer

AKHIL MATHEW picture AKHIL MATHEW · Jun 28, 2017

You can use Connection.open attribute.

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

if conn.open:
    # do something

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