I\'m not sure if this is possible, but I\'m looking for a way to reconnect to mysql database when the connection is lost. All the connections are held in a gevent queue but that
The easiest way is to check the connection right before sending a query.
You can do this by creating a small class that contains two methods: connect
and query
:
import pymysql
import pymysql.cursors
class DB:
def connect(self):
self.conn = pymysql.connect(
host=hostname,
user=username,
password=password,
db=dbname,
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor,
port=3306)
def query(self, sql):
try:
cursor = self.conn.cursor()
cursor.execute(sql)
except pymysql.OperationalError:
self.connect()
cursor = self.conn.cursor()
cursor.execute(sql)
return cursor
db = DB()
Now, whenever you send a query using db.query("example SQL")
the request is automatically prepared to encounter a connection error and reconnects using self.connect()
if it needs to.
Remember: This is a simplified example. Normally, you would want to let PyMySQL help you escape special characters in your queries. To do that, you would have to add a 2nd parameter in the query
method and go from there.