c++sqlqtsqliteqsqlquery

QSqlQuery size() always returns -1


QSqlQuery query;
QString queryText("SELECT * FROM section");
query.exec(queryText);
qDebug() << query.size(); //always -1
while (query.next()) qDebug() << query.value(0).toString(); //got 16 records

Method size() always returns -1.


Solution

  • query.size() is not supported with SQLite. But you can get the number of rows with a workaround.

    QSqlQuery::last () retrieves the last record in the result, if available, and positions the query on the retrieved record. After calling last() you can retrieve the index of the last record and position the query before the first record using first() and previous():

    int numberOfRows = 0;
    if(qry.last())
    {
        numberOfRows =  qry.at() + 1;
        qry.first();
        qry.previous(); 
    }