Qt Qt - Dealing with Databases Remove Database connection correctly


Example

If we want to remove some database connection from the list of database connections. we need to use QSqlDatabase::removeDatabase(),however it's a static function and the way it work is a little wired.

// WRONG WAY
  QSqlDatabase db = QSqlDatabase::database("sales");
  QSqlQuery query("SELECT NAME, DOB FROM EMPLOYEES", db);
  QSqlDatabase::removeDatabase("sales"); // will output a warning

  // "db" is now a dangling invalid database connection,
  // "query" contains an invalid result set

The correct way that Qt Document suggest us is below.

  {
      QSqlDatabase db = QSqlDatabase::database("sales");
      QSqlQuery query("SELECT NAME, DOB FROM EMPLOYEES", db);
  }
  // Both "db" and "query" are destroyed because they are out of scope
  QSqlDatabase::removeDatabase("sales"); // correct