Important: Please read the Qt Code of Conduct -

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

  • Lifetime Qt Champion

    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 2017

    @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