The solution of multithreading problem in QT database (Qsqldatabase can only be used in the thread that created it)

Source: Internet
Author: User
Tags sqlite



The QT database generated by qsqldatabase::adddatabase () Qsqldatabase can only be used in the thread that created it, and it is not supported to use a connection in multithreading or to create a query in another thread
Almost no article in the country mentioned this issue, these days in the database stress test encountered a

Suppose you have the following code:


bool openDatabase()
{
    QSqlDatabase db;
    QString connectionName = "sqlite";
    db = QSqlDatabase::addDatabase("QSQLITE", connectionName);
    db.setDatabaseName("/jyxtec.db");
    if (db.open())
        return true;
    else
        return false;
}


void testQuery()
{
    QSqlQuery query(QSqlDatabase::database("sqlite"));
    query.exec("SELECT * from t_test");
    // ..........
}



Testquery () Here is not supported for multithreaded calls and can only be used in threads that call OpenDatabase (). Otherwise it is easy to segment the error.
There are two ways to resolve this:
1) Create qsqldatabase of different connectionname in each thread that calls Testquery
such as thread A
Qsqldatabase::adddatabase ("Qsqlite", "A");
Qsqlquery query (qsqldatabase::d atabase ("A"));

Thread B
Qsqldatabase::adddatabase ("Qsqlite", "B");
Qsqlquery query (qsqldatabase::d atabase ("B"));



2) Implement a database thread pool, create n different connectionname qsqldatabase, all the query commands are put into this thread pool processing.



Too handsome to go out. Programmer Group: 31843264



Http://blog.chinaunix.net/uid-20680966-id-4779621.html



The solution of multithreading problem in QT database (Qsqldatabase can only be used in the thread that created it)


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.