开发者

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);
        }
        Q开发者_如何学编程SqlDatabase::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?


  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.


Just give your connections different names:

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

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

    return a.exec();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜