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


  • Qt Champions 2016

    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.


  • Qt Champions 2016

    @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 through QSqlDatabase::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.



  • @kshegunov

    This is the solution i used :)


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.