postgresqlqt5qsqlquery

QSqlQueryModel prepared statement (using QSqlQuery) not working


I have a problem using QSqlQueryModel with prepared statement. When executing the statement manually everything works fine, but when binding it to the model - it doesn't execute. On the other hand when I set the model with a "static" query (via QString) - the model executes and loades the data. What am I doing wrong?

I prepere the query like this:

QSqlQuery query;
query.prepare(QString("SELECT \
        kontrahentid \
        , trim(format ('%s %s %s', kontrahentnazwafirmy, kontrahentnazwisko, kontrahentimie) ) as nazwa \
    FROM kontrahent \
    WHERE %1 ilike ? \
").arg(searchBy));
query.addBindValue(searchString);

And it works when querying like this:

if (query.exec()) {
    while (query.next()) {
        qDebug() << "{" << query.value(0) << ", " << query.value(1) << "}";
    }
}

In postgres log I have prepare statement, and executing it the moment after. But when binding it to the model it doesn't work:

QSqlQueryModel* model = new QSqlQueryModel(this);
model->setQuery(query);
//model->setQuery("SELECT kontrahentid, trim(format ('%s %s %s', kontrahentnazwafirmy, kontrahentnazwisko, kontrahentimie) ) as nazwa FROM kontrahent");
if (model->lastError().isValid()) {
    qDebug() << model->lastError();
    return;
}

for (int i = 0; i < model->rowCount(); ++i) {
    //int id = model.record(i).value("id").toInt();
    //QString name = model.record(i).value("name").toString();
    qDebug() << model->record(i).value(0) << model->record(i).value(1);
}

In postgres log I only have the prepare statement, no sign of executing... But when uncommenting the line with "static" query (and commenting the one above it) it works all fine...

What am I doing wrong? do i have to run execute() on the query object before binding it to the model?


Solution

  • do I have to run execute() on the query object before binding it to the model?

    Yes. The doc for QSqlQueryModel::setQuery(const QSqlQuery & query) says:

    Note that the query must be active and must not be isForwardOnly().

    For a query to be active, it must has been executed. The doc for QSqlQuery says:

    Successfully executed SQL statements set the query's state to active so that isActive() returns true. Otherwise the query's state is set to inactive. In either case, when executing a new SQL statement, the query is positioned on an invalid record. An active query must be navigated to a valid record (so that isValid() returns true) before values can be retrieved.