[Qt-interest] Using a single MySQL Connection in the whole project

Dan White ygor at comcast.net
Wed Aug 4 19:41:15 CEST 2010


Wow.  I missed that
<http://doc.qt.nokia.com/4.6/qsqldatabase.html#database>

It's a static method, input the database name and it returns the connection.
Very nice.
The Trolls continue to impress and amaze.

“Sometimes I think the surest sign that intelligent life exists elsewhere in the universe is that none of it has tried to contact us.”
Bill Waterson (Calvin & Hobbes)

----- Luis Lezcano Airaldi <luislezcair at gmail.com> wrote:
> 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!
> _______________________________________________
> Qt-interest mailing list
> Qt-interest at trolltech.com
> http://lists.trolltech.com/mailman/listinfo/qt-interest





More information about the Qt-interest-old mailing list