Unsolved DB unique instance
-
Hello,
I don't know how to share the connection between 2 class.
Should i use the singleton design pattern ?Thanks for help
-
hi
Qt can share the default connection/db internally.
So you can open db in one class
and if you use QSqlQuery in rest of program and if you dont supply
DB to QSqlQuery , it will use this default one.The class holding the DB must of course live on.
-
@Zoptune said:
Should i use the singleton design pattern ?
No. You shouldn't ever use that unless you're aware of its many, many drawbacks.
To expand a bit on @mrjj's answer, you can name your connections when creating them with
QSqlDatabase::addDatabase
, then you can retrieve your connection by its name throughQSqlDatabase::database
. Something like this:// In class 1, main() or w/e QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "mysqlite"); //< Create sqlite connection, name it // In class 2 QSqlDatabase db = QSqlDatabase::database("mysqlite"); //< Use the name to retrieve the connection
If you're using only one connection in your program, then you can skip the names (Qt provides a default name), so you can do it simply like:
// In class 1, main() or w/e QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); //< Create sqlite connection, and use the default name // In class 2 QSqlDatabase db = QSqlDatabase::database(); //< Get the connection with the default name
Kind regards.
-
This is the solution i used :)