简体   繁体   中英

Java & MySQL - Create a login authentication

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM