0

I have a small function like this

bool QcgDatabase::onceindb(const QString& userId)
{
    mDb->prepareSqlQuery("SELECT count(*) FROM mytable WHERE userid=:userId;", "database");
    mDb->prepareBindValue(":userId", userId);
    mDb->sqlExec();

    bool d = mDb->sqlQuery().isActive();
    QVariant c = mDb->sqlQuery().value(QString("count(*)"));
    int e = c.toInt();

    if (e == 1) {
        return true;
    }
    else {
        return false;
    }
}

When I do this command in SQL, the result looks like this

sql

I just want to take value 2 for comparison below, but in the code when I debug, QVariant c always return invalid, therefore e is always = 0. I thought my SQL command is not active, but when I debug, bool dalways return true. Do you guys know why? how can I receive 2 as expected ?

Community
  • 1
  • 1
trangan
  • 341
  • 8
  • 22

1 Answers1

0

Your problem is that you're trying to fetch the result from a column with a special (and in some places invalid) name count(*). You can set an alias for the column and fetch the value using that column alias:

...
mDb->prepareSqlQuery("SELECT count(*) as count FROM mytable WHERE userid=:userId;", "database");
...
QVariant c = mDb->sqlQuery().value("count");
...

And checking return values for error states is also good practice...

Murphy
  • 3,827
  • 4
  • 21
  • 35