Web Hosting Philippines, Offshore Programming, Offshore SEO Philippines, Cheap Webhosting Manila Philippines
Home -> Resources -> Python -> Avoiding MySQL Error 2006 ('Server has gone away') messages

In Spyce, we use a convention where we tuck away the connection details in a module,

import MySQLdb
con=MySQLdb.Connect( host="foobar.com",

dbfoobar.py above, which is in a directory that is outside the locations served by the web server, (e.g. /usr/spyce-2.1/modules/dbfoobar.py). This is to avoid inadvertently leaking login details to the outside world.

However, because MySQLdb.Connect() cannot get called each time a Spyce script is run this way, you will get an Error 2006 ('Server has gone away') exception if you have not called the script for a while and its connection times out. The way to deal with this is to use the mysql ping() function:

from dbfoobar import con


The method above ensures an automatic reconnection if the server ever goes away and should no longer display the error 2006 message. The pydoc documentation for ping() has full details:

>>> import MySQLdb

>>> help(MySQLdb._mysql.connection.ping)
Help on method_descriptor:

    Checks whether or not the connection to the server is
    working. If it has gone down, an automatic reconnection is

    This function can be used by clients that remain idle for a
    long while, to check whether or not the server has closed the
    connection and reconnect if necessary.

    New in 1.2.2: Accepts an optional reconnect parameter. If True,
    then the client will attempt reconnection. Note that this setting
    is persistent. By default, this is on in MySQL<5.0.3, and off

    Non-standard. You should assume that ping() performs an
    implicit rollback; use only when starting a new transaction.
    You have been warned.

 Want to tip via bitcoin?

(address string below for double checking)

© by Andy Sy
last updated: 2009-Jul-26

Web Development / Rich Internet Applications (RIA) Development

Programming Languages


Database Development

VPS Hosting, Ruby on Rails hosting Philippines, RoR hosting, Philippines VPS and VDS
   © 2003-2019 Neotitans Technologies Inc.