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.

5
  • Did you try to check what query.exec(...) calls return? Commented Apr 14, 2023 at 9:06
  • @vahancho yes, it returns true or false Commented Apr 14, 2023 at 9:28
  • Aren't you just looking for QSqlQuery::lastError? Commented Apr 14, 2023 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 Commented Apr 14, 2023 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? Commented Apr 14, 2023 at 10:50

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.