How to switch SQL Database at runtime with model.



  • So I connect to a database like this:

    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("database.db");
    db.open();
    
    QSqlTableModel model;
    

    This works fine the model points to the db connection. which is the default connection. See the constructor here:

    QSqlTableModel::QSqlTableModel(QObject *parent = nullptr, QSqlDatabase db = QSqlDatabase())
    

    Now for some reason I want to set the database later in the program. So I tried this:

    db = QSqlDatabase::addDatabase("QSQLITE");
    
    QSqlTableModel model;
    
    db.setDatabaseName("database.db");
    db.open();
    

    This does not work. If I check directly after model:

    qDebug() << db.isOpen()
    

    It returns true. The db is open.

    I also tried then:

    db = QSqlDatabase::addDatabase("QSQLITE");
    
    QSqlTableModel model;
    
    db.close()
    db.setDatabaseName("database.db");
    db.open();
    

    But still the model does not show anything from the db.

    So Short question:

    I have a model in my app which points to a SQLDatabase. Do I have to create a new model when I want to switch to annother database?

    Do I have to destroy the whole model and create a new one in its place?


  • Lifetime Qt Champion

    Hi,

    You can also try to call setQuery passing the new database connection.

    But in any case, QSqlTableModel is meant to be used with an established connection.

    Otherwise you should go with the base class and reset the query when changing your database. Depending on what you do, you should consider naming your connections and be explicit about them. It will make your logic easier to follow.



  • The problem is I also use this model in qml.

    So that means in QML ever time I change the database I have to create a new model?

    I was thinking about swapping the new model with Loader in QML.

    Also in reality it is not directly QSQLModel. It is a class derived from it defining already a specific format for the tables. So setQuery is not an option in this case-


  • Lifetime Qt Champion

    Can you explain why you need to switch to different databases ?


Log in to reply