Refresh the database connection if connection drops or times out

Robbo_UK picture Robbo_UK · Apr 26, 2013 · Viewed 7.7k times · Source

I have a Symfony command line task that has a habit of dropping the mysql connection.

Its a data import task. Which fetches data from multiple connections. Its not one big query but a few smaller ones.

It seems to drop the connection the first time it is ran. About half way through the script. However the second time its ran (from the beginning) it always completes the task.

Its not timing out on the query as the error response I get is that the connection has been dropped and it runs ok on its own. So im thinking that its some kind of timeout issue that is avoided when its ran the second time due to query caching speeding up the script.

So my question is how do I refresh the database connection?

[Doctrine\DBAL\DBALException]
SQLSTATE[HY000]: General error: 2013 Lost connection to MySQL server during query

Answer

Leroy picture Leroy · Sep 18, 2015

A different approach is to check if Doctrine is still connected to the MySQL server through the ping() method in the connection. If the connection is lost, close the active connection since it is not really closed yet and start a new one.

if(FALSE == $em->getConnection()->ping()){
    $em->getConnection()->close();
    $em->getConnection()->connect();
}