Qt World Summit: Submit your Presentation

Why can't QSqlDatabase be a dynamic variable?

  • I have my connection working via odbc in Linux using


    but it fails when I put :

    db_ptr=new QSqlDatabase();

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

    Is it by design that static should be used?

  • Moderators

    define it fails

  • Lifetime Qt Champion


    Actually it compiles fine here

    auto db_ptr=new QSqlDatabase();


    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


    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