prince_ade prince_ade - 4 months ago 15
SQL Question

Check username and password in java DataBase and give wrong password message if false

i want to display an error wrong username & password after comparing entered username and password with database of users in java.

the problem is it does the if else statement against each row until it gets to the right row b4 displaying "username and password correct" but i want it to check against all and if it doesn't exist then it displays "Please Check Username and Password "

note: please ignore the naming convention the problem is in the arrangement of the while, if and any other recommended loop statements but i am not sure on how to organise it to get my desired result

here is my code with comments

public void displayUsers(String f, String s) {
try {
String queryString = "SELECT SName, SPwd FROM staff";
ResultSet results = Statement.executeQuery(queryString);

while (results.next()) {
String staffname = results.getString("snameeee");
String password = results.getString("SPwd");

if ((f.equals(staffname)) && (s.equals(password))) {

JOptionPane.showMessageDialog(null, "Username and Password exist");
}else {

//JOptionPane.showMessageDialog(null, "Please Check Username and Password ");
}
results.close();
} catch (SQLException sql) {

out.println(sql);
}

Answer

First don't store password in plain text.Secondly loading all records is very wrong approach of doing above code.

   public void displayUsers(String f, String s) {
    try {
        String queryString = "SELECT * FROM staff where SName=? and SPwd=?";
        //set this values using PreparedStatement
        ResultSet results = ps.executeQuery(queryString); //where ps is Object of PreparedStatement

        if(!results.next()) {

              JOptionPane.showMessageDialog("Wrong Username and Password.");  
        }

    } catch (SQLException sql) {

        out.println(sql);
    }finally{
      //closing ResultSet,PreparedStatement and Connection object
    }