How To Implement Retries For Sql Connection Initialization?

Hello friends,

I am wondering how to implement retries for SQL connection initialization with yii. Sometimes on my site I’m seeing “General error: 2006 MySQL server has gone away”. Event this error if I try to refresh 1 second after that everything is ok.

Well I want to set or to implement reconnect when this error happens. Do you know how it could be achieved with Yii?

Thanks in advance!

Did you search the web?

For example I have found this:


Yes sure, but there is no answer for the problem…


I don’t think that my answer will solve your problem but it could put you on the right way.

Here is the code and, after that, a few lines of text :D :


// stores application db connection

private $_dbConnection = Yii::app()->db;


try {

    $this->_dbConnection->createCommand('SELECT 1 FROM customers')->queryScalar();			

} catch (Exception $e) {

    Yii::log('OLD CONNECTION DIED. SETTING UP A NEW DB CONNECTION', 'spooler_ifo', 'spooler.handler');

    $this->_dbConnection = new CDbConnection(Yii::app()->db->connectionString, Yii::app()->db->username, Yii::app()->db->password);					


The above snippet refers to a PHP daemon script of mine which is inactive for long times and, as such, it sometimes needs to re-establish the connection with the database (persistent does not mean forever :D).

It siply uses a "bait" query to determine whether the connection is available or not and, if not, it creates a new one.

Adjusting this snippet to suite your needs could alleviate your problem, anyway I think it is quite strange for a machine which is not under a heavy load having to re-establish database connection every now and then. You should maybe consider to watch for some mis-configured settings.