0

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.

kometen
  • 6,536
  • 6
  • 41
  • 51
  • Did you try to check what `query.exec(...)` calls return? – vahancho Apr 14 '23 at 09:06
  • @vahancho yes, it returns true or false –  Apr 14 '23 at 09:28
  • Aren't you just looking for [`QSqlQuery::lastError`](https://doc.qt.io/qt-6/qsqlquery.html#lastError)? – G.M. Apr 14 '23 at 10:24
  • @G.M. No, because it is not important to me what is the error. If it was happened, 99% it is connection lost, so i just want to know, if connection turned to enable again, am i need to reopen db, or `exec()` will executes succesfully automaticly at this moment –  Apr 14 '23 at 10:46
  • @G.M. Good example about `QSqlQuery::lastError`. If it will return `ConnectionError`, and after this database becames available, next `query.exec()` will be work fine or i need to try to reopen connection after `ConnectionError`? –  Apr 14 '23 at 10:50

1 Answers1

0

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.

mugiseyebrows
  • 4,138
  • 1
  • 14
  • 15