0

I created db handling class with Qt's SQL :

// constructor of my db handler class
DBHandler::DBHandler(QObject *parent) : QObject(parent)
{
  QSqlDatabase db = QSqlDatabase::addDatabas("QMYSQL", "mydb");
  // ... initialization like setUserName(), setPassword()
  if(!db.open())
  {
    QSqlDatabase::removeDatabase("mydb"); // ---- (1)
  }
}

// destructor of my db handler class
DBHandler::~DBHandler()
{
  QSqlDatabase db = QSqlDatabase::database("mydb");
  // ---- (2) ----
  if(db.isOpen())
  {
    db.close();
  }
  db = QSqlDatabase();
  QSqlDatabase::removeDatabase("mydb");
  // ---- (2) ----
}

This class is created at program startup, then performs a query using multiple member functions (inside each member function, get a QSqlDatabase instance through database("mydb").) and finally deleted at program termination.

As in (1) or (2), do I need to explicitly call the close() function or removeDatabase function?

Or is it automatically cleaned up (assuming no connections or queries remained)?

What is correct way of QSqlDatabase clean up?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Dean Lee
  • 95
  • 6
  • According to the documentation you should remove a database after closing it. Removing without closing can cause problems. Destroying a database automatically closes it. – vahancho May 13 '20 at 07:48
  • @vahancho Yes I read it. However, that means I need to call the close() before calling removeDatabase(). I was wondering if I should call removeDatabase() even if there were no connections or queries left at the end of the program. I know that many Qt objects are destroyed when the parent is destroyed. Does this work similarly without calling removeDatabase? – Dean Lee May 13 '20 at 09:12
  • 1
    Everything depends on what you want to achieve. If you don't need the connection anymore, you should remove it after closing. For example, if you remove the "foo" database and than call `QSqlDatabase::database("foo")` it will return an invalid connection. To sum it up: remove connection if you don't want to reuse it. – vahancho May 13 '20 at 09:22
  • @vahancho Um, thanks to the comments, I think I got a hint. – Dean Lee May 13 '20 at 09:31

0 Answers0