1

I'm developing an app which uses a MySQL database. The user may leave the app running for days but most of the time the app isn't using the database. Anyway the connection should be kept active. And I'm wondering what's the appropriate approach to verify if the connection actually is still alive?

Should I do a simple query every 5 seconds to verify it?

A related question.

Community
  • 1
  • 1
KcFnMi
  • 5,516
  • 10
  • 62
  • 136
  • 1
    Maybe not literally every *5* seconds, but sounds like a sensible approach. (Combined with checking the actual openess status). You won't get signals out of QSqlDriver if the DB connection gets severed (and QSqlDatabase isn't a QObject). – peppe Mar 25 '16 at 10:44
  • It'll be interesting to know the reason why there is no such a signal. – KcFnMi Mar 25 '16 at 11:46
  • 1
    Well, do the native (C) APIs for databases notify you of a lost connection? Maybe just nobody bothered... – peppe Mar 25 '16 at 11:50

2 Answers2

2

Not really, you should use the method bool QSqlDatabase::isOpen to check if the database connection is open. It returns true if the connection is open, otherwise, it returns false.

B026
  • 63
  • 6
  • How often? I was expecting a signal to inform about that. – KcFnMi Mar 25 '16 at 03:10
  • 1
    When you call `bool QSqlDatabase::open` the connection is established and will be closed when you call `void QSQlDatabase::close`. So, it's not necessary. But, if you want, you should analyze your system and decide how often must to be. Maybe, in every step, every 10 minutes, 1 hour, a day. You decide it. – B026 Mar 25 '16 at 03:23
  • 1
    Would you believe `bool QSqlDatabase::isOpen()` returns true after MySQL server was shutdown? – KcFnMi Mar 25 '16 at 03:43
  • Agreed that isOpen() does return true when communication is lost (network disconnect) - but attempting queries will throw errors. The first error will be different, indicative of the disconnection. – CodeShane Aug 31 '21 at 19:17
0

bool QSqlDatabase::IsOpen() only checks if connection was oppened, but not if it is still active (at least with MySql).

Using a simple SELECT 1 is much more reliable.