Root0x
Root0x

Reputation: 123

Qt SQL query.exec Always Returning True

Im creating a login system in qt using a database but when I run the query in qt it is always returning true, even when that item is false.

The sql database connection code is below

QSqlDatabase login = QSqlDatabase::addDatabase("QSQLITE");
login.setDatabaseName("/Users/Daniel/Dropbox/Stock_Control.sqlite");
if(!login.open())
    ui->label->setText("Unable To Connect To Database");

The SQL query code is below

static Home *home = new Home;
QSqlQuery query;
QString Username = ui->Username_lineEdit->text();
QString Password = ui->Password_lineEdit->text();
if(query.exec("SELECT * FROM Program_account WHERE Login = '"+ Username +"' AND Password = '"+ Password +"' "))
{
    tries = 0;
    home->show();
    close();
}

Thank you

Upvotes: 0

Views: 2367

Answers (1)

Super-intelligent Shade
Super-intelligent Shade

Reputation: 6449

QSqlQuery::exec() returns true when the query is executed successfully, even if the query is empty. Use QSqlQuery::size() function to check if the query is empty or not.

UPDATE

Since QSqlQuery::size() always returns -1 for sqlite, you can use QSqlQuery::first() instead.

You can do something like:

if(!query.exec("SELECT Login FROM Program_account WHERE Login = '"+ Username +"' AND Password = '"+ Password +"' "))
{
    // something is terribly wrong
}
else if(!query.first())
{
    // incorrect username or password
}
else
{
    tries = 0;
    home->show();
    close();
}

Upvotes: 1

Related Questions