简体   繁体   English

QSqlQuery size()始终返回-1

[英]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. 方法size()始终返回-1。 Help, please. 请帮助。 Thanks. 谢谢。

query.size() is not supported with SQLite. SQLite不支持query.size() 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. QSqlQuery::last ()检索结果中的最后一条记录(如果可用),并将查询定位在检索到的记录上。 After calling last() you can retrieve index of the last record and position the query before the first record using first() and previous() : 调用last()您可以检索最后一条记录的索引,并使用first()previous()在第一条记录之前定位查询:

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

From doc: 来自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. 返回结果的大小(返回的行数),如果无法确定大小,或者数据库不支持报告有关查询大小的信息,则返回-1。 Note that for non-SELECT statements (isSelect() returns false), size() will return -1. 请注意,对于非SELECT语句(isSelect()返回false),size()将返回-1。 If the query is not active (isActive() returns false), -1 is returned. 如果查询未激活(isActive()返回false),则返回-1。

To determine the number of rows affected by a non-SELECT statement, use numRowsAffected(). 要确定受非SELECT语句影响的行数,请使用numRowsAffected()。

http://qt-project.org/doc/qt-4.8/qsqlquery.html#size 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. 您的查询是isSelect并处于活动状态,但SQLite是查询大小无法直接使用的数据库之一。

To prove call this for example: 为了证明这称为例如:

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

It returns false 它返回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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM