9
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. Help, please. Thanks.

Nejat
  • 31,784
  • 12
  • 106
  • 138
Efog
  • 1,155
  • 1
  • 15
  • 33

3 Answers3

14

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(); 
}
Nejat
  • 31,784
  • 12
  • 106
  • 138
4

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

Jablonski
  • 18,083
  • 2
  • 46
  • 47
  • Thanks, but how can i get number of rows then? – Efog Oct 21 '14 at 19:55
  • @Efog I don't know specific of your task, but if you want determine size then you can't do this, if you need number of rows in future you can use additional int variable as counter and use it, but sqlite can't help you here. – Jablonski Oct 21 '14 at 20:05
2

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;
}
Ivan Romanov
  • 1,138
  • 1
  • 9
  • 24