中英文建设网站,上海申远建筑设计有限公司,深圳专业网站,如何做论文网站如果你用过Qt的QSqlDatabase的话#xff0c;多半会对下面的警告信息感兴趣#xff1a; QSqlDatabasePrivate::removeDatabase: connection qt_sql_default_connection is still in use, allqueries will cease to work. 意思是说#xff0c;还有某查询引用默认数据库连接多半会对下面的警告信息感兴趣 QSqlDatabasePrivate::removeDatabase: connection qt_sql_default_connection is still in use, allqueries will cease to work. 意思是说还有某查询引用默认数据库连接qt_sql_default_connection。 如果忽略该警告Qt官方文档里也写了可能会出现内存泄漏 Warning: There should be no open queries on the database connection when this function is called,otherwise a resource leak will occur. 还是不出现这个警告的好。怎么把它弄没了呢我把一切外围的对象都排除了仅建立一个连接打开它然后关闭连接调用removeDatabase()。居然还有警告问题已经锁定在我关闭连接的语句上 QSqlDatabase::removeDatabase(QSqlDatabase::database().connectionName()); 默认连接的名字也是默认的需要通过connectionName()函数获得。这样写貌似没什么问题后来调试发现QSqlDatabase::database()静态函数实际上使默认连接的引用计数1。上述句子相当于 QSqlDatabase db QSqlDatabase::database();//获得实例。
QString name db.connectionName();//获得默认连接名。
QSqlDatabase::removeDatabase(name);//删除默认连接。 这样问题就清晰了db获得了一个引用此时引用计数为2。在调用removeDatabase()时db对象并没有被删除默认连接的引用计数仍为2于是报告警告信息。 我们只需将其改为 QString name;{name QSqlDatabase::database().connectionName();}//超出作用域隐含对象QSqlDatabase::database()被删除。QSqlDatabase::removeDatabase(name); 问题就解决了 如果直接打默认连接名的话代码就简单多了不过名字不太好打再说了万一Qt把默认连接名改了呢 QSqlDatabase::removeDatabase(qt_sql_default_connection);//不推荐。 下面是官方文档摘录 Warning: There should be no open queries on the database connection when this function is called, otherwise a resource leak will occur. Example: // WRONGQSqlDatabase 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 to do it: {QSqlDatabase db QSqlDatabase::database(sales);QSqlQuery query(SELECT NAME, DOB FROM EMPLOYEES, db);}// Both db and query are destroyed because they are out of scopeQSqlDatabase::removeDatabase(sales); // correct转载于:https://www.cnblogs.com/codingmylife/archive/2010/04/27/1722404.html