QT 子线程调用主线程的MySQL连接

出错问题:

  • QSqlDatabasePrivate::database: requested database does not belong to the calling thread
  • QSqlDatabasePrivate::removeDatabase: connection ‘qt_sql_default_connection’ is still in use, all queries will cease to work

解决方法

主线程、子线程各自创建数据库连接,用完断开数据库连接

移除连接的句子

QSqlDatabase::removeDatabase(linkName);
void DBConnect::disConnect()
   {
	   QString connection;
	   connection = m_DB.connectionName();
	   m_DB.close();
	   m_DB = QSqlDatabase();
	   m_DB.removeDatabase(connection);
   }

注意:如果操作顺序如下,并在一个函数中,依然会出现第二个错误 

QSqlDatabase db = QSqlDatabase::database();
QString name = db.connectionName();
QSqlDatabase::removeDatabase(name); 

修改为:修改作用域范围

QString name;
{
  QSqlDatabase db = QSqlDatabase::database();
  name = db.connectionName();
}
QSqlDatabase::removeDatabase(name); 

你可能感兴趣的:(QT,数据库,qt,mysql,数据库)