PDA

View Full Version : validation of username and password



malavika
21st November 2011, 15:04
hey ,

i wish to compare my username and password to my values put in a table say login table.

i'm able to do this validation by using variables within program as follows:


usr="leo";
pass="123";

if(!(ui->lineEdit->text()== usr && ui->lineEdit_2->text() == pass))
{
m.setText(" Username and Password don't match ! ! ! ! Try Again");
m.exec();
}
if(ui->lineEdit->text()== usr && ui->lineEdit_2->text() == pass)
{
hide();
home *homewindow = new home(this);
homewindow->show();
}


this works but i want to compare with values in my database ! please help ! thanks in advance ! ! !

qlands
23rd November 2011, 14:13
Hi,

For this you need a database connection. So you need:

Code in the header of the class (for example mainwindow.h)


#include <QtSql>
...
private:
QSqlDatabase db;

...


Code in the implementation file (cpp)


db = QSqlDatabase::addDatabase("QSQLITE","dblite"); //Add a database connector to SQLite. You just need to call this once. Put it in the constructor for example

//Process for validating the user and pass using a table in sqlite
db.close();
db.setDatabaseName("./myDatabase.sqlite");
if (!db.open()) //Try to opens the database
{
QMessageBox::critical(0, qApp->tr("Cannot open database"),
qApp->tr("Unable to establish a SQLite connection to the database\n\n"
"Click Cancel to exit."), QMessageBox::Cancel);
}
else
{
QSqlQuery querylite(db); //Create a query using db
QString sql; //SQL statement
sql = "SELECT count(userName) from MyUsersTable WHERE userName = '";
sql = sql + ui->lineEdit->text() + "'";
sql = sql + " AND password = '";
sql = sql + ui->lineEdit2->text() + "'";

if (querylite.exec(sql)) //Executed the statement
{
if (querylite.value(0).toInt() > 0) //If the return is bigger that 0
{
//User and pass was found
}
else
{
//No access
}
}
else
{
//Error with the sql
}
}
db.close();


Carlos

Lykurg
23rd November 2011, 16:56
Hi,

don't use QSqlDatabase as a private member, that could cause problems on quiting the application. Better use every time you need a database object the static method QSqlDatabase::database(). Use the optional parameter to identify which database connection you like.