PDA

View Full Version : QSqlDatabase - How to connect to multiple database?



cutie.monkey
10th March 2010, 07:09
Hi all,

Is it possible to connect to multiple database with different server/host at the same time? If yes, how?

I'm currently trying to connect to two different database, one in localhost and other in a network PC. I'm establishing connection using QSqlDatabase,



QSqlDatabase defaultDB = QSqlDatabase::addDatabase( "QMYSQL" );
defaultDB.setUserName( "root");
defaultDB.setPassword( "" );
defaultDB.setHostName( "localhost" );
defaultDB.setPort( 3306 );

if(!defaultDB.open()){
QMessageBox::information(this, "Connection Failed!", defaultDB.lastError().text(),
QMessageBox::Ok, QMessageBox::NoButton);
return;
}


then I want to create another database connection, with host: 192.168.0.1




QSqlDatabase DB = QSqlDatabase::addDatabase( "QMYSQL" );
DB.setUserName( "root");
DB.setPassword( "" );
DB.setHostName( "192.168.0.1" );
DB.setPort( 3306 );

if(!DB.open()){
QMessageBox::information(this, "Connection Failed!", DB.lastError().text(),
QMessageBox::Ok, QMessageBox::NoButton);
return;
}


but after the second database is open, I got this warning:



QSqlDatabasePrivate::removeDatabase: connection 'qt_sql_default_connection' is still in use, all queries will cease to work.
QSqlDatabasePrivate::addDatabase: duplicate connection name 'qt_sql_default_connection', old connection removed.


Thank you very much!

Lykurg
10th March 2010, 07:13
Have a look in the Ddocumentation!!! Just use the second parameter of addDatabase().

ChrisW67
10th March 2010, 07:16
Give one or both connections a name in QSqlDatabase::addDatabase()

toutarrive
10th March 2010, 09:46
Without giving a name at least to one of the connection, there will be both 'considered' as the default one.
As suggested, giving a name will differentiate them from each other.

cutie.monkey
10th March 2010, 13:03
Thanks, its working..

Cheers!