Reputation: 1179
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.
Upvotes: 10
Views: 5707
Reputation: 32635
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 the 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();
}
Upvotes: 15
Reputation: 18504
From QSqlQuery::size:
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().
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 this, call this for example:
qDebug() <<db.driver()->hasFeature(QSqlDriver::QuerySize);
It returns false
.
Upvotes: 6
Reputation: 21
I get the same problem when using qsqlite in qt5. query.size always return -1, so i use query.first() instead.
QString username = ui->usernameInput->text();
QString password = ui->passwordInput->text();
QString command = "SELECT * FROM user WHERE username = '" + username + "' AND password = '" + password + "'";
QSqlQuery query;
if (query.exec(command)) {
qDebug() << query.size(); // the size will always -1 when using QSqlite
if (query.first()) { // so i use query.first() to check if there has any result
QMessageBox::information(this, "Login success.", "You have successfully logged in!");
} else {
QMessageBox::information(this, "Login failed.", "Please Check the username and password");
}
}
Upvotes: 2
Reputation: 1228
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;
}
Upvotes: 3