c++ - How to Handle Database Connections in Qt? -


Here's my problem; In this situation, it complains about the duplicate connection with the same connection name:

  test :: test (the name of the consignment connection) {db = QSqlDatabase :: addDatabase ("QMYSQL", connectionName ); } Int main (int argc, char * argv []) {QString connectionName = QString ("test"); QQAPER AP (AGRC, AGRV); Test myDb (connectionName); Test myDb2 (connectionName); Back a.exec (); }  

My solution here:

  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"); QQAPER AP (AGRC, AGRV); Test {MyDb (connectionName); Test myDb2 (connectionName); } QSqlDatabase :: removeDatabase (connectionName); Back a.exec (); }  

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

2-) Do you have another suggestion?

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

  1. -
  2. I have a of the code section I am not being executed every time the test class. You can have a setup function to do this work.
  3. No, it is not so. This design is usually not required to create / open a new DB connection every time you create a class instance.

Comments