PDA

View Full Version : A database question



Morea
29th January 2009, 22:54
I have a class, and now I wish to add database connections to the constructor for that class.
I have code like



for (int i=0;i<nr_of_connects;i++)
{
QString name("mydb_con");
name.append(QString(i));
X = QSqlDatabase::addDatabase("QMYSQL",name);
X.open();
}

The problem is the "X" part. What do I write there? Should I declare a QList<QSqlDatabase> in the class or QList<QSqlDatabase*> ?

I will not know how many database connections there will be at compile time :-(

mm78
30th January 2009, 00:04
addDatabase() returns a QSqlDatabase object and nothing but a QSqlDatabase object so X has to be of type QSqlDatabase.

Anyhow, QSqlDatabase will handle all the connections for you behind the scenes so you don't have to put them in a list - or keep them around at all. Just use QSqlDatabase::database() whenever you need one of the connections that you have created.

Relevant docs:
http://doc.trolltech.com/4.4/qsqldatabase.html#addDatabase
http://doc.trolltech.com/4.4/qsqldatabase.html#database