Search code examples
c++sqlqsqlqueryqsqldatabase

QSqlquery prepare() and bindvalue() not working?


I have this code for managing logins, here is a small bit of it:

void Login::on_pushButton_clicked(){
    QString user, password;
    user = ui->username->text();
    password = ui->pass->text();

    QSqlQuery qry;
    qry.prepare("SELECT id, name from users WHERE username = :username AND password = :password");
    qry.bindValue(":username", user);
    qry.bindValue(":password", password);{
    int counter = 0;
    while (qry.next()){
        counter++;
    }
    if(counter==1)
        ui -> statuslabel -> setText("Sign in successful");
    if(counter<1)
        ui -> statuslabel -> setText("Sign in unsuccessful");
    }
}

On giving it the correct input (ie correct password and username) it does not work and proceed to the second if condition saying that Sign in is unsuccessful. I have a counter int type that counts how many instances of user input match the database tables. It is initialized to a zero which means that is not the problem. any ideas on what might be the case here?


Solution

  • You forgot to call qry.exec() before accessing first element using qry.next(). It should be called after last qry.bindValue().

    Below is example how it can be done in your code:

    QSqlQuery qry;
    qry.prepare("SELECT id, name from users WHERE username = :username AND password = :password");
    qry.bindValue(":username", user);
    qry.bindValue(":password", password);
    qry.exec()
    if(!qry.isActive())
    {
        ui -> statuslabel -> setText("SQL Statement execution failed");
        return;
    }
    if(qry.size() > 0)
        ui -> statuslabel -> setText("Sign in successful");
    else
        ui -> statuslabel -> setText("Sign in unsuccessful");
    

    Note: You don't have to use QSqlQuery::next to check if your SELECT statement return any result. QSqlQuery::size method will return number of selected rows.