QSqlQueryModel complains that my database is not open

1.3k Views Asked by At

I am trying to use QSqlQueryModel in order to retrieve some values from my database like such:

 QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL", "test1");
 db.setHostName(Vars::strDbHost);
 db.setDatabaseName(Vars::strDbName);
 db.setPort(Vars::strDbPort);
 db.setUserName(Vars::strDbUsername);
 db.setPassword(Vars::strDbPassword);

 db.open()

 QSqlQueryModel model;
 model.setQuery(QString("SELECT * FROM users WHERE login=%2").arg(Vars::strUserLogin));

But I keep getting a QSqlQuery::exec: database not open error.

Why is this, and how can I correctly use QSqlQueryModel to retrieve the values I want?

1

There are 1 best solutions below

0
On BEST ANSWER

You are calling the wrong version of setQuery. This only works with db which have the default name. In your case, you need to call void QSqlQueryModel::setQuery(const QString &query, const QSqlDatabase &db):

model.setQuery(QString("SELECT * FROM users WHERE login=%2").arg(Vars::strUserLogin)
               , db);