2

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?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
metdos
  • 13,411
  • 17
  • 77
  • 120

2 Answers2

3

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.

Alexander Konstantinov
  • 5,406
  • 1
  • 26
  • 31
2

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.

David
  • 692
  • 8
  • 21
  • As Alexander says in his answer `wait_timeout` can be used to change the timeout so if 8 hours is too much for you, that's easy to modify. Otherwise, a TCP connection is stateless. If you are not transmitting data, you can disconnect the Ethernet cable for the night, reconnect in the morning and your connections will resume as expected. In Qt the `isOpen()` is just a memory flag anyway. Finally, I have apps that run 24/7/365 and there are period of times when 8 hours can pass without hits... although it is relatively rare. – Alexis Wilke Jan 10 '19 at 21:04