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.