有没有其他更好的方法来获取数据库凭据并将其与 java 进行比较?

Is there any other better way to get and compare database credentials with java?

我正在尝试使用 mySQl 数据库创建一个 java 的简单登录系统。

我已将用户 ID 和密码存储在数据库中 table。 我想出了一种登录方式,它似乎运行良好,但我不确定这是否是正确的方式,因为我找不到任何登录系统的在线资源。

我的步骤是:

  1. 正在获取用户的输入(用户 ID 和密码)。
  2. 使用我创建的 fetch() 方法遍历 table 并找到这个特定的 ID。
  3. 如果找到,从 table 中获取密码和余额并将它们存储在变量中。
  4. 最后将我之前从数据库中获取并存储在变量中的密码与用户输入的密码进行比较。

我很清楚以纯文本形式存储密码是一个很大的安全漏洞,但现在我只是想学习如何使用我 [=34= 中的数据库中的数据] 程序

这是我的代码:

public class firstjava extends Database {

    public static int UID = 0;
    public static String password;
    public static int BAL;
    public static String upassword;

    static void fetch(int userid) throws SQLException {
        String query = "SELECT * FROM Persons";
        Statement st = con.createStatement();

        ResultSet rs = st.executeQuery(query);

        while (rs.next()) {
            int ID = rs.getInt("pid");
            if (ID == UID) {
                password = rs.getString("password");
                BAL = rs.getInt("balance");
            }

        }
        if (upassword.equals(password)) {
            System.out.println("you are now logged in");
        } else {
            System.out.println("incorrect password");
        }
        st.close();
    }

    public static void menu() throws IOException, SQLException {
        Scanner atm = new Scanner(System.in);
        System.out.println("enter your account number");
        UID = atm.nextInt();
        System.out.println("enter your account password");
        upassword = atm.next();
        fetch(UID);
    }

    public static void main(String[] args) throws IOException, SQLException {
        Database db = new Database();
        try {
            db.connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        menu();
        db.close();
    }
}

"If I have been able to see further, it was only because I stood on the shoulders of giants."

这是巨人:

https://spring.io

您会发现如下内容:

Optional<User> r = userRepo.findByName(name);
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
if (passwordEncoder.matches(password, user.getPassword())) {
   // ...
}

您可以直接将 userId 作为参数传递给您的查询并从数据库中获取密码和余额 Table 然后您应该将密码与用户输入的密码进行比较。

static void fetch(int userid) throws SQLException
{
    PreparedStatement ps = null;
    ResultSet rs = null;

    String query = "SELECT * FROM Persons where pid = ?";
    PreparedStatement ps = con.prepareStatement(query);
    ps.setInt(1,userid);
    rs = ps.executeQuery(); //instantiate rs with executed query

    while(rs.next()) {
        password = rs.getString("password");
        BAL = rs.getInt("balance");
    }   
    if(upassword.equals(password)) {
        System.out.println("you are now logged in");
    } else {
        System.out.println("incorrect password");
    }
    rs.close();
    ps.close();    
}