QSqlDatabase singleton class problems



  • hello guys,

    I am thinking how is the best way to made a program using QSql, how to organize it most clear possible, i made this class, but it didn't load mysql driver, where i made a mistake, if you know a best way to do this, help me, thanks alot!

    #ifndef DATABASE_H
    #define DATABASE_H
    
    #include <QSqlDatabase>
    #include <QDebug>
    
    class Connection: public QSqlDatabase{
        private:
            Connection(){}
    
        public:
            static Connection &getInstance(){
                static Connection conn;
                if(!conn.contains("sisdeposito")){
                    conn = Connection();
                    conn.addDatabase("QMYSQL");
                    conn.setHostName("127.0.0.1");
                    conn.setPort(3306);
                    conn.setDatabaseName("sisdeposito");
                    conn.setUserName("root");
                    conn.setPassword("aaxd31");
                    if(conn.open())
                        qDebug() << "Conectado";
                }
                return conn;
            }
    };
    
    #endif // DATABASE_H
    
    


  • @LodiCode
    I'm not sure if you had add sql support in .pro files

    Second, Have you compiled your database driver for MySQL?



  • @Kevin-Zhong

    yes i add it, my problem is class Connection : public QSqlDatabase,

    i set static Connection conn;
    and conn.addDatabase("QMYSQL");

    but if i change all Connections in getInstance for QSqlDatabase, it work, but it is correct? have other way to do it?

    thanks for you time.


  • Moderators

    @LodiCode Why do you need such a class? QSqlDatabase can already manage as many connections as you need, see here http://doc.qt.io/qt-5/qsqldatabase.html. You can use the default connection or give your connections names and access them by names.
    Regarding MySQL driver: what does http://doc.qt.io/qt-5/qsqldatabase.html#drivers return? How did you install Qt and which version?


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.