Python:MySQL:处理超时

Nup*_*pur 5 python mysql timeout

我使用的是Python和mySQL,查询之间存在很长的延迟.结果,我得到一个'MySQL连接已经消失'错误,即wait_timeout被超过.

这已经在例如优雅地处理"MySQL已经消失"中进行了讨论

但这并没有具体回答我的问题.

所以我处理这个问题的方法 - 我已经将所有sql执行语句包装在一个方法中 -

  def __execute_sql(self,sql,cursor):
    try:
        cursor.execute(sql)

    except MySQLdb.OperationalError, e:            
        if e[0] == 2006:
            self.logger.do_logging('info','DB', "%s : Restarting db" %(e))
            self.start_database()
Run Code Online (Sandbox Code Playgroud)

我在代码中有几个地方调用此查询.问题是,我也有几个游标,所以方法调用看起来像 -

self.__execute_sql(sql,self.cursor_a)
self.__execute_sql(sql,self.cursor_b)
Run Code Online (Sandbox Code Playgroud)

等等

在db启动后,我需要一种方法来优雅地重新执行查询.我可以在if语句中包装调用,然后重新执行它

def __execute_sql(self,sql,cursor):
    try:
        cursor.execute(sql)
        return 1
except MySQLdb.OperationalError, e:            
    if e[0] == 2006:
        self.logger.do_logging('info','DB', "%s : Restarting db" %(e))
        self.start_database()
        return 0
Run Code Online (Sandbox Code Playgroud)

然后

if (self.__execute_sql(sql,self.cursor_a) == 0):
   self.__execute_sql(sql,self.cursor_a)
Run Code Online (Sandbox Code Playgroud)

但这很笨重.有一个更好的方法吗?谢谢!!!

小智 2

我遇到了同样的问题,想包装异常来捕获它,但我通过使用以下方法解决了它。在调用execute之前,调用
self.con.ping(TRUE)

http://www.neotitans.com/resources/python/mysql-python-connection-error-2006.html http://mysql-python.sourceforge.net/MySQLdb.html

我无法再找到我发现此问题的原始资料,但这立即解决了问题。

  • 在运行查询之前进行 Ping 被认为是一种反模式,会浪费资源且不可靠:https://www.percona.com/blog/2010/05/05/checking-for-a-live-database-connection-considered-有害/ (2认同)