'qt_sql_default_connection' is still in use

出现这个告警是因为打开了多个db而没有及时关闭,网上搜了答案是使用完了执行

QSqlDatabase::removeDatabase(m_connectionName);

泄漏的问题有所改善,但点快了仍然有问题,研究了自己的代码才发现,原来自己每次 query时都open一下,即使每次查完后都关闭也来不及的。

将open 和 close函数放在构造和析构中执行;问题解决;

openSQL

 

void Worker::openDatabase()
{
    QDateTime dateTime = QDateTime::currentDateTime();
    QString m_dbName = "zzz";
    m_connectionName = "m_dbName";
    m_connectionName += dateTime.toString("_yyyyMMdd_hhmmss");

    m_db = QSqlDatabase::addDatabase("QMYSQL", m_connectionName);
    if  (!m_db.isValid()) {
        qDebug()<<"openDatabase not valid";
        return ;
    }

    m_db.setHostName("localhost");
    m_db.setUserName("root");
    m_db.setPassword("root");
    m_db.setDatabaseName(m_dbName);

    if (!m_db.open()) {
        qDebug()<<"openDatabase not open";
        return ;
    }
    m_query = new QSqlQuery(m_db);
}

 

closeSQL

 

 

void Worker::closeDatabase()
{
    if(m_query != NULL )
    {
        delete m_query;
        m_query = NULL;
    }

    if (m_db.isValid()) {
        if (m_db.isOpen())
            m_db.close();
        m_db = QSqlDatabase::database("", false);
        QSqlDatabase::removeDatabase(m_connectionName);
    }
    qDebug()<<"closed;";
}

 

最后是工作函数

void Worker::slot1()
{
    QString str = "delete from test where id > 300000 ";
    QString str1 = "UPDATE test SET content = 'Checked' WHERE content = 'Wilson' ";
    QString str2 = "update test set content = 'zero.' where content > '10000' ";

    qDebug()<<"3 slots1  : "<<QThread::currentThreadId();
    tmpTime.start();
    m_db.transaction();
    for (int i = 0 ; i < 100000 ; i++ )
    {
        QString str3 = QString("insert into test(content) values('[Checked]')");
        m_query->exec(str3);
        globalVar++;
    }
    m_query->exec(str1);
    m_query->exec(str2);
    m_query->exec(str);

    m_db.commit();
    qDebug()<<"Time Elapsed: "<<tmpTime.elapsed()<<" ms";

#if 0
    while(m_query->next()) //query.next()指向查找到的第一条记录,然后每次后移一条记录
    {
        int ele0 = m_query->value(0).toInt();
        QString ele1 =m_query->value(1).toString();
        QString ele2 = m_query->value(2).toString();
        qDebug() << ele0 <<ele1 <<ele2 ;
    }
#endif

    qDebug()<<"query done.";
    emit sig1();

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

1, Developing utilities.

2, Wellknown linuxc

3,. wellknown qt

 

 

 

 

 

===================================

compile mysql for qt

 

你可能感兴趣的:('qt_sql_default_connection' is still in use)