QSqlQuery size() always returns -1

半世苍凉 提交于 2019-12-23 09:36:40

问题


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.


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



回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/26495049/qsqlquery-size-always-returns-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!