Lion King
Lion King

Reputation: 33813

How to get the count of rows

I want to get the count of rows from last query.
I have used size() and numRowsAffected() functions, but none of them work.

I have written the following code:

int counter = 0;
QStringList TableHeader;
QSqlQuery qry;
qry.prepare("SELECT *, (SELECT COUNT(*) FROM users) AS count FROM users");
qry.exec();

qDebug() << qry.value("count").toString(); // <<-- print the count of rows

ui->tableWidget->setRowCount(10);
ui->tableWidget->setColumnCount(3);
TableHeader << "Username" << "Password" << "Age";
ui->tableWidget->setHorizontalHeaderLabels(TableHeader);
while (qry.next()) {
    ui->tableWidget->setItem(counter, 0, new QTableWidgetItem(qry.value("username").toString()));
    ui->tableWidget->setItem(counter, 1, new QTableWidgetItem(qry.value("password").toString()));
    ui->tableWidget->setItem(counter, 2, new QTableWidgetItem(qry.value("age").toString()));
    ui->tableWidget->item(counter, 0)->setData(Qt::UserRole, qry.value("id").toString());
    counter++;
}

But unfortunately this does not work fine and gives me an error QSqlQuery::value: not positioned on a valid record.

I want to get the count of rows whether by using a query or function.

Upvotes: 4

Views: 1899

Answers (1)

Nejat
Nejat

Reputation: 32665

qry.size() is not supported with SQLite. 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(); 
}

Upvotes: 4

Related Questions