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?
- --
- I would prefer adding the Database connection in a
static
portion of code. Not executing everytimeTest
class is initialized. You can have asetup
function to handle all that work. - 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();
}
精彩评论