title: Python: MySQL: Handling timeouts
body: <p>I am using Python and mySQL, and there is a long lag between queries. As a result, I get an 'MySQL connection has gone away' error, that is wait_timeout is exceeded.</p>
  
  <p>This has been discussed e.g. in 
  <a href="https://stackoverflow.com/questions/1987701/gracefully-handling-mysql-has-gone-away">Gracefully handling &quot;MySQL has gone away&quot;</a></p>
  
  <p>but this does not specifically answer my query.</p>
  
  <p>So my approach to handling this -
  I have wrapped all my sql execute statements in a method as  -</p>
  
  <pre><code>  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()
  </code></pre>
  
  <p>I have several places in the code which calls this query. The thing is, I also have several cursors, so the method invocations look like-</p>
  
  <pre><code>self.__execute_sql(sql,self.cursor_a)
  self.__execute_sql(sql,self.cursor_b)
  </code></pre>
  
  <p>and so on</p>
  
  <p>I need a way to gracefully re-execute the query after the db has been started. I could wrap the calls in an if statement, and re-execute so it would be </p>
  
  <pre><code>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
  </code></pre>
  
  <p>and then</p>
  
  <pre><code>if (self.__execute_sql(sql,self.cursor_a) == 0):
     self.__execute_sql(sql,self.cursor_a)
  </code></pre>
  
  <p>But this is clunky. Is there a better way to do this?
  Thanks!!!</p>