There is no way to "avoid" this error. This error happens when you lose connection to the DB server. This can happen for a variety of reasons. The most common reason for the MySQL server has gone away
error, is that the server timed out and closed the connection.
Some other common reasons are:
- You (or the db administrator) has killed the running thread.
- You tried to run a query after closing the connection to the server.
- You got a timeout from the TCP/IP connection on the client side.
- You have encountered a timeout on the server side and the automatic reconnection in the client is disabled.
- And more.
Check out this link from the MYSQL docs for more info.