PDA

View Full Version : Problem with Multi Thread Query



olekhanchai
27th May 2012, 18:47
I read two articles of internet "Asynchronous Database Access with Qt 4.x" from http://www.linuxjournal.com/article/9602
I use these code to implement the program that use network for query some of data but I got some problem that is :

1. it's warning when I reconnect to server
QSqlDatabasePrivate::removeDatabase: connection 'test.db' is still in use, all queries will cease to work.
QSqlDatabasePrivate::addDatabase: duplicate connection name 'test.db', old connection removed.

How can I implement these code to connect database once without reconnect it again when clients connect to server and can connect more than one database for multithread query?

2. If I want to return data to client in object and receive object from client side. What's the solution can solve?


This is my attach source code.
7756

Thanks for any help.

Spitfire
29th May 2012, 11:30
Solution is quite simple.

You can't add new database connection for every worker with the same name.
You can or create single connection to each database and then get that connection by name in each worker, or you can create database connection for each worker with different name.
Depending on what you need first and second approach may be as good.

To remove the warning you get (following first approach from above), replace addDatabase( driver, connection_name ) with database( connection_name ) in your Worker constructor.
The actual connection (using addDatabase() ) create in your server constructor (or anywhere else you think it appropriate):


Worker::Worker(int ID, QObject* parent )
: QObject( parent )
{
m_database = QSqlDatabase::database( "test.db" );
}

Server::Server(QObject *parent) :
QTcpServer(parent)
{
QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE", "test.db" );
db.setDatabaseName("test.db");
if ( !db.open() )
{
qWarning() << "Unable to connect to database, giving up:" << db.lastError().text();
return;
}
}