[Qt-interest] Using a single MySQL Connection in the whole project
Luis Lezcano Airaldi
luislezcair at gmail.com
Wed Aug 4 19:14:20 CEST 2010
El 04/08/10 11:55, David Villalobos Cambronero escribió:
> Hi all,
>
> My name is David, I'm really new in Qt.
>
> I'm writing an application to learn it, but I have found a problem
> while trying to connect to MySQL.
>
> Here is the scenario:
>
> I have a MDI Widget where I'll add some classes with information, i.e
> a widget showing the MySQL server status an other to show the MySQL
> Variables.
>
> I can connect successfully to MySQL with the following statement:
>
> QSqlDatabase mainServerConnection = QsqlDatabase::addDatabase("QMYSQL");
>
> In addition I have a class that shows a form for collecting the
> connection parameters.
>
> But, How can I use the mainServerConnection in other classes, I have
> tried to make it public, but the addDatabase seems not to work. Here
> is what I tried:
>
> In MainClass.h
> public:
> QSqlDatabase *mainServerConnection;
>
> In MainClass.cpp
> mainServerConnection = new QSqlDatabase;
> mainServerConnection->addDatabase("QMYSQL");
>
> How can I use a just one MySQL Connection in my whole project?
>
> And many thanks for the help.
>
> PD: BTW I'm not American, so my English is bad, please be patient.
>
> Best regards
> David
>
There's already a Singleton implementation for the database connections.
When you create the database conenction (I do it in main() ) you do:
QSqlDtabase db = QSqlDatabase::addDatabase("QMYSQL", "db_name");
I don't know if this is the right way, but this is how I do it:
//class definition
class SomeClass {
private:
QSqlDatabase db;
}
//class implementation (it can be the constructor or another method)
db = QSqlDatabase::database("db_name");
Saludos!
More information about the Qt-interest-old
mailing list