Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 875
Efog Avatar asked Oct 21 '14 19:10

Efog


3 Answers

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(); 
}
like image 106
Nejat Avatar answered Nov 20 '22 14:11

Nejat


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

like image 28
Kosovan Avatar answered Nov 20 '22 13:11

Kosovan


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;
}
like image 25
Ivan Romanov Avatar answered Nov 20 '22 12:11

Ivan Romanov