问题
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