4

I receive the following everyday. My scripts are running through cron jobs. Can anyone help to fix this?

 File "/usr/lib64/python2.6/site-packages/MySQLdb/cursors.py", line 174, in execute
    self.errorhandler(self, exc, value)
  File "/usr/lib64/python2.6/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorclass, errorvalue
_mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away')

My code:

def get_id(test_mysql_conn,id):
    cursor = test_mysql_conn.cursor()
    cursor.execute("""select id from test where id = %s """, (id))
    row = cursor.fetchone()
    if row is not None:
      return row[0]
    return 0
Brisi
  • 1,781
  • 7
  • 26
  • 41

2 Answers2

1

Try the follwing

if (os.getenv('SERVER_SOFTWARE') and os.getenv('SERVER_SOFTWARE').startswith('Google App Engine/')):
            db = MySQLdb.connect(unix_socket = UNIX_SOCKET + INSTANCE_NAME, host =" HOST/IP", db = "DB_Name", user = "User_Name") //if your mysql is on google server
        else:
            db = MySQLdb.connect(host = "HOST/IP", port = "Port_number", db = "DB_name", user = "User_Name", passwd = "password")

    cursor = db.cursor()
    cursor.connection.autocommit(True)

except Exception, err:
    logging.info("Error In DataBase Connection : " + traceback.format_exc())
    return 'DataBaseProblem'        
try:
    sql = query+str(req_args)
    logging.info("QUERY = "+str(sql))
    cursor.execute(sql)
    procedureResult = cursor.fetchall();
    if str(procedureResult) == '()':
        logging.info("Procedure Returned 0 Record")
        procedureResult = 'DataBaseProblem'


    #logging.info("procedureResult : " + str(procedureResult))
except Exception, err:
    #trackBack = str (traceback.format_exc())
    #raise Exception('DataBaseProblem',trackBack)
    procedureResult="DataBaseProblem"

for mysql port number is 3306

Sunil Kumar
  • 655
  • 1
  • 7
  • 12
0

This happens when you open a MySQL connection but don't close it. There's a timeout on MySQL's side of things.

One thing you can do is close the connection when you're done using it. Another would be to use an ORM that supports this or pooling built in (SQLAlchemy is one I believe.)

Ryan O'Donnell
  • 617
  • 6
  • 14