View Full Version : Detecting QSqlDatabase disconnections

5th October 2011, 17:57
I'm working with both QMYSQL and QODBC drivers. Both drivers work fine as long as the database is working. If the database server goes offline, QSqlDatabase fails to detect it, and all the calls to isOpen() keep returning "true", no matter that all the queries are failing.

As a workaround, I'm subclassing QSqlQuery, to rewrite exec() so that if the query fails, and the error number corresponds to a disconnected database (this is driver-dependant, as QSqlError::type is bullshit and always returns QSqlError::StatementError, instead of QSqlError::ConnectionError :(). However I see no way for accessing the QSqlDatabase that was passed to the QSqlQuery constructor, so that I can close it, and driver().close() doesn't work either because "driver()" is const. It's weird that there's no database() method in QSqlQuery, I hope it's for a good reason, but I guess I'll have to store my own m_database if I want to make things work.

I bet someone here must have dealt with this problem before, as detecting when your database goes offline seems to me as a very basic feature (that Qt should implement). Am I going in the wrong direction? Does anyone know of a better solution? Mine just feels overcomplicated for such a basic feature.

5th October 2011, 18:09
QSqlDatabase doesn't know because it is not told so by database when it is about to die. To know whether alive or not you can send something like select 1 (from table) query timely or before you intend to issue your query.