QSqlQuery size() always returns -1 QSqlQuery size() always returns -1 sqlite sqlite

QSqlQuery size() always returns -1


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 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(); }


From doc:

Returns the size of the result (number of rows returned), or -1 if the size cannot be determined or if the database does not support reporting information about query sizes. Note that for non-SELECT statements (isSelect() returns false), size() will return -1. If the query is not active (isActive() returns false), -1 is returned.

To determine the number of rows affected by a non-SELECT statement, use numRowsAffected().

http://qt-project.org/doc/qt-4.8/qsqlquery.html#size

Your query isSelect and active but SQLite is one of the databases for which the size of the query is not directly available.

To prove call this for example:

qDebug() <<db.driver()->hasFeature(QSqlDriver::QuerySize);

It returns false


For myself I use this function

int sqlSize(QSqlQuery query){    int initialPos = query.at();    // Very strange but for no records .at() returns -2    int pos = 0;    if (query.last())        pos = query.at() + 1;    else        pos = 0;    // Important to restore initial pos    query.seek(initialPos);    return pos;}