I have a Manager class that saves data in the SQL table and also get result from SQL table and test these data.when I run my program,one frame will be shown that gets ID and pas
Because you're hauling the entire database table down into Java's memory and testing every row in a while loop. You don't break the loop if a match is found so that it continues overwriting the boolean outcome until with the last row.
That said, you really don't want to do the comparison in Java. Just make use of the SQL WHERE clause. That's much more efficient and really the task a DB is supposed to do. Don't try to take over the DB's work in Java, it's only going to be inefficient.
public boolean exists(String username, String password) throws SQLException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
boolean exists = false;
try {
connection = database.getConnection();
preparedStatement = connection.prepareStatement("SELECT id FROM client WHERE username = ? AND password = ?");
preparedStatement.setString(1, username);
preparedStatement.setString(2, password);
resultSet = preparedStatement.executeQuery();
exists = resultSet.next();
} finally {
close(resultSet);
close(preparedStatement);
close(connection);
}
return exists;
}
You see that I made a few enhancements:
To learn more about using JDBC the proper way you may find this basic tutorial useful.
The simple answer is that your while loop should terminate when you find a match, so it should read:
while (rst.next() && bool == false) {
if (rst.getString(1).equalsIgnoreCase(userName) && rst.getString(2).equalsIgnoreCase(password)) {
bool = true;
}
}
Note that it would be more efficient to select only rows that match your user id & password, something along the lines of the following: (note that error handling is left as an exercise for the reader)
PreparedStatement stmt;
stmt = conn.prepareStatement("SELECT yahooId , password FROM clienttable WHERE yahooId = ?");
stmt.setString(1, "userName");
ResultSet rst = null;
rst = stmt.executeQuery();
if (rs != null && rs.getString("password").equals(password)) { bool = true; }