Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Handle Database Connections in Qt?

Here my problem; in such a case it complains about duplicate connections with same connection name:

Test::Test(QString connectionName)
{
    db=QSqlDatabase::addDatabase("QMYSQL",connectionName);
}

int main(int argc, char *argv[])
{
    QString connectionName=QString("test");
    QCoreApplication a(argc, argv);

    Test myDb(connectionName);
    Test myDb2(connectionName);

    return a.exec();
}

Here my solution:

Test::Test(QString connectionName)
    {
        if(!QSqlDatabase::contains(connectionName))
            db=QSqlDatabase::addDatabase("QMYSQL",connectionName);
        else
            db=QSqlDatabase::database(connectionName);
    }

    int main(int argc, char *argv[])
    {
        QString connectionName=QString("test");
        QCoreApplication a(argc, argv);
        {
            Test myDb(connectionName);
            Test myDb2(connectionName);
        }
        QSqlDatabase::removeDatabase(connectionName);

        return a.exec();
    }

1-)Is this a good way to handle this problem?

2-)Do you have another suggestion?

3-)Do you think that this is a drawback for Qt?

like image 960
Rob Ashton Avatar asked Nov 14 '22 07:11

Rob Ashton


1 Answers

  1. --
  2. I would prefer adding the Database connection in a static portion of code. Not executing everytime Test class is initialized. You can have a setup function to handle all that work.
  3. No, it's not. It's by design. Usually you should not have to create/open a new DB connection every time you create a class instance.
like image 86
Pablo Santa Cruz Avatar answered Dec 10 '22 03:12

Pablo Santa Cruz