My question is about reconnecting to MySQL server if any error encounters.
I am connecting to the MySQL server in Flask:
connection = pymysql.connect(host='host',
user='user',
connect_timeout= 31536000,
password='passwd',
db='db_name',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
and for the query using the cursor as well: Flask route code:
@app.route("/chart", methods=['GET', 'POST'])
def chart():
try:
with connection.cursor() as cursor:
#line chart open tickets
query = "select createdDate,rootCause,requestId from db_name;"
df = pd.read_sql(query, connection)
print(df)
except pymysql.MySQLError as e:
print(e)
I want to reconnect to db when I get the error:
pymysql.err.OperationalError: (2006, "MySQL server has gone away (TimeoutError(110, 'Connection timed out'))")
Please help me find the solution for this error.
How to reconnect to the database when any error encounters.
Thanks in advance!
Looks like you are using a single connection forever. Try to create a new connection every time and close it once the required queries are run. This issue can be avoided through this.