QSqlDatabase connection issue
-
Hi! I have the application witch requires connection to
Databaseon the server. It all works well but after 4 minutes of inactivity ofDBconnection it displays errors.
I know the problem is with
wait_timeoutvariable onDB serverbut I can't change it because I don't have permission to the server. On the server it has value of 240 seconds = 4 minutes.I have added some check to execute query and it will check connection:
Code:
void Test::dbTest() { QSqlQuery sqlQuery("some query", QSqlDatabase::database("ConnectionName")); sqlQuery.setForwardOnly(true); if (sqlQuery.size() > 0) { // Some action } else { int errorCode = sqlQuery.lastError().number(); if (errorCode == 2013) { QSqlDatabase::database("ConnectionName").open(); // opens DB connection dbTest(); // runs recursively } else { qDebug() << sqlQuery.lastError().text(); } } }It fixes such situation but I need to add such check for all functions that works with
DB. But what if I can omit such check and everywhere just runQSqlDatabase::open()before query? What will happen when connection is still alive andQSqlDatabase::open()function will run again, it will create another connection or use existing? Thanks. -
Hi,
What about using a heartbeat on that connection ?
-
Yes, it also will work. But I have checked
QSqlDatabase::open()solution onWAMPand it creates only 1 connection toDB. Thanks. -
You should take a look at the QSqlDatabase::setConnectOptions and the specifics for MySQL. You could fine tune the timeout for your server.
-
You should take a look at the QSqlDatabase::setConnectOptions and the specifics for MySQL. You could fine tune the timeout for your server.
I have added
setConnectOptions("MYSQL_OPT_RECONNECT=TRUE");and now it automatically reconnects. Thanks.