Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh the database connection if connection drops or times out

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

like image 950
Robbo_UK Avatar asked Apr 26 '13 10:04

Robbo_UK


People also ask

When should I open a database connection?

Usually you'd only want to open a connection to your database when you need to use that connection. Keeping connections open can increase the chance that part of your code will accidentally, or maliciously through the actions of others, cause unwanted queries to be performed on the database.


1 Answers

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();
}
like image 134
Leroy Avatar answered Sep 18 '22 18:09

Leroy