When running query against a database the following error can be generated:
ERROR 2006 (HY000) at line NNN: MySQL server has gone away
Where “NNN” is the line number of the script currently being run where the error occurred.
Possible Causes and Resolution
This is a general error which can have a number of possible causes. The one certainty is that the MySQL database is no longer listening on the connection – but this does not necessarily mean that MySQL is no longer available.
MySQL has crashed.
Check that MySQL is still running on the server. If it is not running and this was not a planned shutdown then it is reasonable to conclude that MySQL has crashed. I personally have never experienced this, but if it happens then investigate whether you can upgrade to a newer version.
MySQL has been shutdown.
Check that MySQL is still running, if it is not and it was shut down (accidentally or intentionally) then that is the cause of the problem. Restart MySQL.
Network connectivity has failed.
Even if the database is still up, is it possible to contact the server? If you can ping the server (or MySQL is running no the localhost) then basic network connectivity is not the problem.
MySQL networking has failed
The problem may be the MySQL connection. If the query was trying to transfer a large block of data then the MySQL packet-size may be set too small.
Try increasing the value of max_allowed_packet and restart the MySQL database service. In MySQL Administrator select “Startup Variables” andon the “Advanced Networking” tab thsi is shown under “Data / Memory size” and is labeled as “Max. packet size.” The default is 1MB and one of my systems now runs at 16MB.
The database connection has timed out and thus the SQL has failed.
Try increasing the wait_timeout, or reconnecting just before firing the query.
Modified after copying from http://www.cryer.co.uk/brian/mysql/trouble_mysql_gone_away.htm