QSqlDatabase connection issue



  • Hi! I have the application witch requires connection to Database on the server. It all works well but after 4 minutes of inactivity of DB connection it displays errors.

    0_1529744896243_connection_error.jpg

    I know the problem is with wait_timeout variable on DB server but 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 run QSqlDatabase::open() before query? What will happen when connection is still alive and QSqlDatabase::open() function will run again, it will create another connection or use existing? Thanks.


  • Lifetime Qt Champion

    Hi,

    What about using a heartbeat on that connection ?



  • @SGaist

    Yes, it also will work. But I have checked QSqlDatabase::open() solution on WAMP and it creates only 1 connection to DB. Thanks.


  • Lifetime Qt Champion

    You should take a look at the QSqlDatabase::setConnectOptions and the specifics for MySQL. You could fine tune the timeout for your server.



  • @SGaist

    I have added setConnectOptions("MYSQL_OPT_RECONNECT=TRUE"); and now it automatically reconnects. Thanks.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.