c++qtqt5qsqldatabase

How to handle if database is already open in Qt?


The problem is that the database connection can be unstable, so at the beginning of the program it is easy to check this with if(!db.open()). But some cases can happen while the application is running.

The point is if db.open() is false. I still need to try and send queries to the DB, so the question is whether does query.exec("...") tries to re-open the database connection if the database is available now, or do I need to do db.open() sooner?

Note. My application is a service running in the background and it is trying to send queries to the DB in an infinite loop and I need to handle an unstable connection.


Solution

  • QSqlQuery::exec does not try to reopen database, it only checks if it's open already.

    Sources:

    QSqlQuery::prepare(const QString& query)

    QSqlQuery::exec()

    QSqlQuery::exec(const QString& query)

    Note that sql operations in qt is not thread-safe, so you can only run queries from same thread you open your database connection, and if you open connection from another thread you cannot use sql models with sql views, for example display QSqlQueryModel in QTableView.