Counting records in a QSqLite db
-
Hi,
I have a QSqLite db and I need to find out the number of records in one of the tables. I currently have the following code, which says I have only one record (the correct number would be 7):while (query_fix.next () == true) { recCount++; query_fix.next (); } qDebug() << "Record count (fixdb): " << recCount;
What did I miss?
Thank you for your help. -
@Venkatesh-V
I tried like this:recCount = query_fix("SELECT COUNT(*) FROM Items");
and I got the following error message:
C:\Programming\Projects\Folkfriends_bzr\checkout\fixdb.cpp:121: error: no match for call to '(QSqlQuery) (const char [27])'
recCount = query_fix("SELECT COUNT(*) FROM Items");
^
Any idea why? -
Hi,
Because that's not how you use a QSqlQuery object.
A
select count
should be handled the same as classicselect
call. You'll just have one result which will contain the number of rows. -
@Venkatesh-V
This returns 1, but there are 7 records in the db. Any idea why?int recNum; recNum = query_fix.prepare ("SELECT COUNT(*) FROM Items"); query_fix.exec (); qDebug() << "Record count in fixdb: " << recNum;
-
hi
If i show you how the function is defined, can you then guess why its 1 ?
bool QSqlQuery::prepare(const QString & query)I will give you a hint and say that
query_fix.exec ();
must be used.
Also the value of true is often 1. -
Or you can also use this,
QSqlQuery q;
q.prepare("SELECT COUNT (*) FROM TableName");
q.exec();
int rows= 0;
if (q.next()) {
rows= q.value(0).toInt();
} -
@Venkatesh-V
This worked.
Thank you.