Check Username and Password in Java Database and Give Wrong Password Message If False

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

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
}

Username and Password not Matching Error Messages in Java

You might need to look up the user by username AND password:

String username = usernametxt.getText();
String password = passwordtxt.getText();
// avoid SQL injection by setting query parameters with '?'
String sql = "SELECT * FROM logininfo WHERE username = ? AND password = ?";
PreparedStatement st = conn.prepareStatement(sql);
st.setString(1, username);
st.setString(2, password );
ResultSet rs = st.executeQuery();
if (!rs.next()) {
// no records found, login failed
JOptionPane.showMessageDialog(null, "Login Information is Incorrect.");
}
else {
// record found, login succeeded
// assuming here that there is a unique constraint in the database
// on (username, password), otherwise multiple records could be found
chg2.setVisible(true);
this.setVisible(false);
}

How to verify username and password in Java-mysql?

Implement the below code:

private void login() {
try {
if (user != null && pass != null) {
String sql = "Select * from users_table Where username='" + user + "' and password='" + pass + "'";
rs = stmt.executeQuery(sql);
if (rs.next()) {
//in this case enter when at least one result comes it means user is valid
} else {
//in this case enter when result size is zero it means user is invalid
}
}

// You can also validate user by result size if its comes zero user is invalid else user is valid

} catch (SQLException err) {
JOptionPane.showMessageDialog(this, err.getMessage());
}

}

login page's error with database retrieval

Following on from @Ravi's answer, if you must loop, I'd suggest the following (extraneous code removed for clarity):

boolean loggedIn = false;

while(rs2.next()) {
if((user.equals(uname)) && (pwd.equals(password))){
loggedIn = true;
break;
}
}

if (!loggedIn) {
JOptionPane.showMessageDialog(this, "Incorrect Username or Password!", "Login Error", JOptionPane.ERROR_MESSAGE);
}


Related Topics



Leave a reply



Submit