简体   繁体   English

Postgre SQL / Java比较数据库中的用户名和散列密码

[英]Postgre SQL/ Java Comparing UserName and Hashed Password in Database

I am trying to implement a function which asks the user to enter their username. 我正在尝试实现一个要求用户输入用户名的功能。 Then checks if the user name entered is in the database. 然后检查输入的用户名是否在数据库中。 The below code is a test code before I start coding more functions. 在开始编写更多函数之前,下面的代码是测试代码。 My problem is that the code doesn't print out when the username entered doesn't exist in the database. 我的问题是,当输入的用户名在数据库中不存在时,代码不会打印出来。 However, it does print out when the username does exist. 但是,当用户名存在时,它会打印出来。 For example, ohm34 exists in the database, so when the program is ran it prints: User Name Does Exist . 例如,ohm34存在于数据库中,因此当程序运行时会打印: User Name Does Exist brian23 doesn't exist in the database so it should print User Name Does Not Exist but it doesn't. brian23在数据库中不存在,因此它应该打印User Name Does Not Exist但它不User Name Does Not Exist The program is ran simply by using java ProgramName 只需使用java ProgramName即可运行该程序

 public void letLogin() throws SQLException
 {
    Scanner stdin;
    String sql;
    Statement select = connection.createStatement();
    String userNames;

    stdin = new Scanner(System.in);

    System.out.print("Enter your user name: ");
    user_name = stdin.next();

  sql = "SELECT " + "user_name " + "FROM" + " users8" + " where 
        user_name = "
        + "'" + user_name + "'";

  r = select.executeQuery(sql);
  if(r.next())
  {
     userNameCounter = r.getString("user_name");
     if(userNameCounter.equals(user_name))
     {
        System.out.println("User Name Does Exist");

     }

     else
     {
        System.out.println("User Does Not Exist");
     }
  }

  } // method letLogin

When you create the query, if the user exists, it will enter on the if(r.next()). 创建查询时,如果用户存在,它将在if(r.next())上输入。 But, if the user does not exists, it will not enter. 但是,如果用户不存在,则不会进入。 You'll have to put the else with the if(r.next()). 你必须把else与if(r.next())放在一起。

Example: 例:

if(r.next())
{
   System.out.println("User Name Does Exist");
}
else
{
   System.out.println("User Does Not Exist");
}

You don't need to get the user with getString(), because you are testing the user on the query, so if the query returns something (r.next() == true), the user exists. 您不需要使用getString()来获取用户,因为您正在对查询进行测试,因此如果查询返回某些内容(r.next()== true),则该用户存在。

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

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