PDA

View Full Version : Check credentials using QSql



death_star
24th January 2011, 08:46
i wrote the following function to make a simple login check.username and password are two global QString variables(values entered by user via a line edit). but this function always returns false for some reason. the commented out query.exec works fine(returns true when user present,false otherwise). i have a feeling its something to do with my query.prepare, but not able to lay my finger on it.any ideas?

bool check_cred()
{
QSqlQuery query;
query.prepare("select * from credentials where uname=':id' and passwd=':pd'");
query.bindValue(":id", username);
query.bindValue(":pd", password);
query.exec();
//query.exec("select * from credentials where uname='ru' and passwd='ru'");
if(query.size()==0)
return false;
else
return true;
}

stampede
24th January 2011, 10:27
Check the values of 'username' and 'password', maybe they are empty strings.
It wont hurt to check this too (after exec()):
QSqlQuery::lastError() (http://doc.qt.nokia.com/latest/qsqlquery.html#lastError)

BalaQT
24th January 2011, 13:03
hi,
ensure tat

select * from credentials where uname='ru' and passwd='ru'
gives any result in database. run the above query in the database and check.
and run the qDebug()<<query.executedQuery(); in db.

Bala

wysota
24th January 2011, 13:07
Get rid of the quotation marks from your query. Also look at my modifications of your query.

bool check_cred()
{
QSqlQuery query;
query.prepare("select COUNT(*) from credentials where uname=:id and passwd=:pd");
query.bindValue(":id", username);
query.bindValue(":pd", password);
if(!query.exec() || !query.next()) return false;
return (query.value(0).toInt()>0);
}
Better yet don't store plaintext passwords but rather some hashes (like sha1 or md5).

death_star
25th January 2011, 13:52
no they are not empty strings.checked that.

@bala the query returns a result in the database, no problem.the commented exec() works fine

@wysota tried the modified code but still the same problem. always returns false.

wysota
25th January 2011, 16:33
This might sound stupid but did you open the database before running the query? Show us the code please.

death_star
26th January 2011, 06:16
Whoa!! you were right wysota! there was something wrong in the code i was using for setting up the connection. should have eliminated all the common problems before running here... Thanks for all the help! used db.setHostName("127.0.0.1"); instead of db.setHostName("localhost");. but still doesnt explain why the commented query worked though.