FDREW
FDREW

Reputation: 13

"Unable to fetch row" error using QSqlQuery

I am trying to write a simple application using Qt and its SQL handling parts. I succeed in connecting to my DB, but I am unable to run any queries on it, whether they are SELECTs or INSERTs. (The database is developed using SQLite3)

Here's the constructor for the class handling the SQL parts:

SQLHandler::SQLHandler(QObject *parent, QString dbname) : QObject(parent)
{
    dbName = dbname;

    database = QSqlDatabase::addDatabase(DATABASE_NAME);
    database.setDatabaseName(dbName);

    connectionState = database.open();
}

And here's a snippet where I'm trying to validate two fields filled by the user:

bool SQLHandler::LoginValidation(const QString username, const QString password)
{
    QSqlQuery loginQuery("SELECT * FROM Cont WHERE Username = " +
                         username + " AND Parola = " + password + ";", database);

    if(!loginQuery.exec())
        qDebug() << loginQuery.lastError() << username << password << loginQuery.lastQuery();

    while( loginQuery.next() )
    {
        if( loginQuery.value(0).toString() == username && loginQuery.value(1).toString() == password )
        {
            return true;
        }
    }

    return false;
}

Whenever I'm running this SELECT, I'm getting an QSqlError("", "Unable to fetch row", "No query") error.

Any help would be much appreciated!

Upvotes: 0

Views: 870

Answers (1)

eyllanesc
eyllanesc

Reputation: 243897

You should not concatenate to build a query since in addition to making it susceptible to an SQL Injection attack you also incorrectly build the query, instead use placeholders:

bool SQLHandler::LoginValidation(const QString & username, const QString & password)
{

    QSqlQuery loginQuery("SELECT * FROM Cont WHERE Username = ? AND Parola = ?", database);
    loginQuery.addBindValue(username);
    loginQuery.addBindValue(password);

    if(!loginQuery.exec()) 
        // ...

Upvotes: 1

Related Questions