skip to Main Content

This is rows in my table.
SQL table

With this code, I get "in" in console.

QSqlQuery qry;
qry.prepare("SELECT * FROM user");
qry.exec();
if(qry.size() > 0)
    qInfo() << "in";
else
    qInfo() << "error";

But with this code, I get "error".

QSqlQuery qry;
qry.prepare("SELECT age FROM user");
qry.exec();
if(qry.size() > 0)
    qInfo() << "in";
else
    qInfo() << "error";

2

Answers


  1. QSqlQuery qry;
    qry.prepare("SELECT age FROM user");
    if(qry.exec()) {
        while(qry.next()) {
            qInfo()<<"in";
        }
    } else {
        qInfo()<<"error";
    }
    
    Login or Signup to reply.
  2. Try

    QSqlQuery qry;
    qry.prepare("SELECT age FROM "user"");
    qry.exec();
    

    The problem is with the table name. Since user is a reserved word, some tools (PgAdmin) automatically add double quotes to the name "user" and you have to use double quotes when applying to the table. Unfortunately user in Postgres is a function (equivalent to current_user) hence the first query returns a row without error.

    The best solution is to rename the table and not use reserved words as Postgres identifiers (the name of a table, column, view, function, etc).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search