I have successfully connected my Java app to MySQL, and then I want the user to input their username and password. Then it would send a query to MySQL and look for a spot with that username, and then compare the password given, with the password in the database. And for the most part, this works. Let's say the username is "ABC" and the password is "def". If when prompted for username, and typed "ABC def" it is saying it is successful, same with a password of "def a". I believe the problem is the rs.next(), and it is checking only for any text before a space.
Any ideas for solutions?
String databaseUsername = "";
String databasePassword = "";
// Check Username and Password
System.out.print("Enter Username: ");
String name = sc.next();
System.out.print("Enter Password: ");
String password = sc.next();
// Create SQL Query
Statement stmt = connection.createStatement();
String SQL = "SELECT * FROM users WHERE users_name='" + name + "' && users_password='" + password+ "'";
ResultSet rs = stmt.executeQuery(SQL);
// Check Username and Password
while (rs.next()) {
databaseUsername = rs.getString("users_name");
databasePassword = rs.getString("users_password");
}
if (name.equals(databaseUsername) && password.equals(databasePassword)) {
System.out.println("Successful Login!\n----");
} else {
System.out.println("Incorrect Password\n----");
}
If the ResultSet
returns a row, the Username and Password have already been checked by the SQL
statement. You do not need to check again. Additionally, you should put in place a system where the same Username can not be used more than once. (Make it Unique
or key on it in the database)
Also, use prepared statements and hashed passwords to avoid injection and other attacks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With