Question

Here my code snippet:

query.next();
qDebug()<<query.lastError();
qlonglong res=query.value(0).toLongLong();
qDebug()<<query.lastError();

and the corresponding log I have:

Debug: QSqlError(2006, "QMYSQL: Unable to execute query", "MySQL server has gone away") 
Warning: QSqlQuery::value: not positioned on a valid record
Debug: QSqlError(2006, "QMYSQL: Unable to execute query", "MySQL server has gone away")

Normally my program works just fine (it works on a server and accepts connections from clients), but every morning when I tried to connect it, I'm getting messages above.

What can be the problem with MySQL server?

Was it helpful?

Solution

From the MySQL Manual:

The most common reason for the MySQL server has gone away error is that the server timed out and closed the connection.

...

By default, the server closes the connection after eight hours if nothing has happened. You can change the time limit by setting the wait_timeout variable when you start mysqld.

...

If you have a script, you just have to issue the query again for the client to do an automatic reconnection. This assumes that you have automatic reconnection in the client enabled (which is the default for the mysql command-line client).

See this manual page for more details on this error.

OTHER TIPS

I know this is old but happens to be the first google hit for "MySQL server has gone away QMYSQL: Unable to execute query".

It seems QSqlDatabase::isOpen() will still return true even though we don't have a connection anymore. Here is how I catch it:

QSqlDatabase db = QSqlDatabase::database();
QSqlQuery query(db);
QString q = "SELECT * FROM myTable;";
if (!query.exec(q))
{
    int err = query.lastError().number();
    if (err == 2006) // Might want to do #2013 here also?
    {
        db.close();
        if (db.open() && !query.exec(q))
        {
            // handle error here we still failed...
        }
    }
    else
    {
        // handle normal query errors here
    }
}

I was able to mimic this situation by restarting the server with "/etc/init.d/mysql restart" and keep sending queries to it and it eventually throws this error. I feel this shouldn't be changed server side, in fact 8 hours seems extremely long to keep an idle connection open.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top