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)