x This domain is for sale. If you intrested, Please contact : webspeckle@gmail.com

How to close a database connection in Qt?

In most cases a warning "QSqlDatabasePrivate::addDatabase: duplicate connection name 'qt_sql_default_connection', old connection removed" occurred while adding or closing database in Qt.

How to solve this problem?

// WRONG
QSqlDatabase db = QSqlDatabase::database("mydb");
QSqlQuery query("SELECT ...", db);
QSqlDatabase::removeDatabase("mydb"); // will output the above warning
//Closing database connection in  CORRECT way
db.close();
db =  QSqlDatabase();
QSqlDatabase::removeDatabase("mydb");
And also you can check the database connection is empty or not.

if(db.connectionName().isEmpty())
{
       //Add database.
}

No comments:

Post a Comment