简体   繁体   English

Java-如何检查MySQL表中是否已经存在用户名

[英]Java - How To Check If Username Already Exists In a MySQL Table

I want to check whether a username already exists in a database table or not. 我想检查database表中是否已经存在username

Java Code: Java代码:

if (e.getSource() == jButton2)
{
  U = jTextField1.getText();
  if (jTextField1.getText().trim().equals(""))
  {
    JOptionPane.showMessageDialog(this, "Please Write Username !");
  } 
  else if (jPasswordField1.getText().equals(""))
  {
    JOptionPane.showMessageDialog(this, "Please Write Password !");
  } 
  else
  {
    try {
      String Driver = "com.mysql.jdbc.Driver"; 
      String URL = "jdbc:mysql://localhost:3306/LoginForm"; 
      Class.forName(Driver); 
      Connection Conn = DriverManager.getConnection(URL, "root", "12345");
      Statement S = Conn.createStatement();
      ResultSet RS = S.executeQuery(
          "SELECT * FROM login where username ='" + U + 
          "' and Password ='" + jPasswordField1.getText() + "'");

      while (RS.next()) {
        String Username = RS.getString("Username");
        String Password = RS.getString("Password");
        String Admin = RS.getString("Admin");

        if (Username.equals(U) & Password.equals(jPasswordField1.getText()) &
          Admin.equals("0")) 
        {

          JOptionPane.showMessageDialog(this, "Logged In Successfully !");
          this.dispose();
          NormalUsers NU = new NormalUsers();
          break;

        } 
        else if (Username.equals(U) & 
          Password.equals(jPasswordField1.getText()) & Admin.equals("1"))
        {

          JOptionPane.showMessageDialog(this, 
            "Logged In Successfully , Opening Administration Panel !");

          this.dispose();
          AdminPanel AP = new AdminPanel();
          break;
        }
        else 
        {
          JOptionPane.showMessageDialog(this, "Invalid Username Or Password!");
        }
      }
    } 
    catch (SQLException | ClassNotFoundException ex)
    {
    }
  }
}

The problem is that: 问题是:

  • If there are no rows in the database , then there is no an error message: Invalid Username or Password . 如果database中没有行,则没有错误消息: Invalid Username or Password
  • When I execute the SQL query manually: SELECT * From Login I see the row exists there, but since I filter on password , it doesn't get into the while loop . 当我手动执行SQL查询时: SELECT * From Login我看到那里存在该行,但是由于我过滤了password ,因此它不会进入while loop

How should I use java to check if a username exists in a MySQL table? 如何使用Java检查MySQL表中是否存在用户名?

For this query type specially, you don't need to loop through the ResultSet. 特别是对于此查询类型,您无需遍历ResultSet。

You're trying to find one determined record. 您正在尝试查找一个确定的记录。 You will not have two records with the same username/password (I'm assuming the primary key of login table is the username), so just a if(rs.next()) it's enough. 您将不会有两个具有相同用户名/密码的记录(我假设登录表的主键是用户名),所以只要一个if(rs.next())就足够了。 If it exists, validate to check if it's an admin. 如果存在,请验证以检查是否为管理员。

Besides, in the query you're already implying that the record must have the specified username and password, no need to test for it once the result set is returned. 此外,在查询中您已经暗示该记录必须具有指定的用户名和密码,一旦返回结果集,就无需对其进行测试。

Just test for the user type, if it's admin, display the accordingly message, else, do the proper. 只需测试用户类型,如果是admin,则显示相应的消息,否则,请执行正确的操作。

If the rs.next() is not met, then the user doesn't exist, so in the else block, you can display the error message about the user not being found or being invalid. 如果不满足rs.next() ,则该用户不存在,因此在else块中,您可以显示有关找不到该用户或该用户无效的错误消息。

The thing you need to work on is MySQL query. 您需要处理的是MySQL查询。 I think a query with the WHERE clause is what you are looking for. 我认为您正在寻找带有WHERE子句的查询。

Also you might want to put that code in a separate class to prevent cooking some spaghetti code . 另外,您可能希望将该代码放在单独的类中,以防止烹饪某些意大利面条代码

The link below is an answer that is related to php language, but what you need to look is the MYSQL query and the logic: Check If Username Exists 下面的链接是与php语言相关的答案,但是您需要查看的是MYSQL query和逻辑: 检查是否存在用户名

Try something like this: 尝试这样的事情:

public String login(String uname, String password) throws Exception{

    String status=null;
    ConnectionHandler handler=new ConnectionHandler(); //class for connection
    Connection con=handler.createConnection();
    Statement stmt=con.createStatement();
    String query="select * from loginTable where username=" +
      "\""+uname+"\""+";";  //get username

    ResultSet rs=stmt.executeQuery(query); 
    String checkUser=rs.getString(1);
    String checkPass=rs.getString(2);
    if(checkUser.equals(uname) && checkPass.equals(password)){
        status="True";
    }
    else{
        status="False";
    }
    con.close();
    return status;
}

Using this status string I determine if the username validates or not. 使用此status字符串,我可以确定用户名是否有效。 Have the SQL do the heavy lifting (as it was designed to do) instead of coding it yourself with java. 让SQL进行繁重的工作(如设计那样),而不是使用Java自己编写代码。

You could do a SELECT COUNT(*) AS total FROM login where username ... Then resultSet.getInt("total") . 您可以SELECT COUNT(*) AS total FROM login where username执行SELECT COUNT(*) AS total FROM login where username ,然后resultSet.getInt("total") If the total is greater than 0 that user already exists. 如果总数大于0,则该用户已经存在。 I would also use a PreparedStatement as it is less vulnerable to sql injection attacks. 我还将使用PreparedStatement,因为它不易受到sql注入攻击的攻击。 Take a look at this https://www.owasp.org/index.php/Preventing_SQL_Injection_in_Java . 看看这个https://www.owasp.org/index.php/Preventing_SQL_Injection_in_Java Example of sql count ... SQL计数示例...

ResultSet RS = S.executeQuery("SELECT COUNT(*) AS total FROM login where username ='" + U + "' and Password ='" + jPasswordField1.getText() + "'");
        while (RS.next()) {
            if( RS.getInt("total") > 0 ) {
                // user already exists
            } else {
                // user does not exist
            }
        }

Assuming only one row is returned you can replace the while loop with an if statement. 假设只返回一行,则可以用if语句替换while循环。 You also don't need to check the username and password after the query has been executed as this is handled by the where clause. 您也不需要在执行查询后检查用户名和密码,因为这是由where子句处理的。 So your query could be modified to: 因此,您的查询可以修改为:

PreparedStatement prest = Conn.prepareStatement("SELECT Admin FROM login WHERE username = ? and Password = ?");
prest.setString(1, U);
prest.setString(2, jPasswordField1.getText());

and then process it using an if statement: 然后使用if语句处理它:

if (rs.next()) {
  //Process user level (Normal or admin)
} else {
  //Incorrect login details
}

我是Java的新手,但我认为您应该检查jPasswordField ,如果它是JTextBox没问题,但是如果它是JPasswordFieldgetText()返回byte[]而不是string,您需要将byte[]转换为string第一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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