Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Why can't QSqlDatabase be a dynamic variable?



  • I have my connection working via odbc in Linux using

    db_static=QSqlDatabase::addDatabase("QODBC","db");
    

    but it fails when I put :

    db_ptr=new QSqlDatabase();
    db_ptr->addDatabase("QODBC","db");
    

    All other db settings are set by the same methods just changing . to ->

    Is it by design that static should be used?


  • Moderators

    @Seb-Tur
    define it fails


  • Lifetime Qt Champion

    Hi

    Actually it compiles fine here

    auto db_ptr=new QSqlDatabase();
    db_ptr->addDatabase("QODBC","db");

    Anyway

    docs says
    "Warning: It is highly recommended that you do not keep a copy of the QSqlDatabase around as a member of a class, as this will prevent the instance from being correctly cleaned up on shutdown. "

    So you dont need to store a pointer to it.

    it has access to it already via QSqlDatabase::database (static call)

    setQuery(SelectStr, QSqlDatabase::database(LOGDBSTR));

    so in 99.999% of all cases you do not need to keep a pointer to it :)


  • Lifetime Qt Champion

    Hi,

    QSqlDatabase is a singleton that manages all the database connections. It's all explained in the documentation of the class.

    Beside that, addDatabase is a static method returning a QSqlDatabase instance so what you are doing has in fact no effect and you are manipulating an invalid QSqlDatabase object.


Log in to reply