5

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----");
    }
  • 3
    Use `PreparedStatement` to avoid SQL injections. Also, what isn't working? – Sotirios Delimanolis Mar 01 '13 at 19:08
  • 2
    1) Don't store plaintext passwords, hash them. 2) If you get any record, then the username and password match so no further check is needed (you do not need to get the value from the database and match it in java). – SJuan76 Mar 01 '13 at 19:09
  • The bigger problem is that if you were to type the Username and Password --> "ABC def" in one line when prompted for the username, it is a successful login. And I want it to be two steps. So "ABC def" would not be a correct username, "ABC" is. – Jonathon Charles Loch Mar 01 '13 at 19:11
  • You probably want `AND` instead of `&&` in the MySQL query – Philip Whitehouse Mar 01 '13 at 19:14

1 Answers1

3

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.