还有其他更好的方法来获取和比较Java的数据库凭据吗?

时间:2018-08-07 08:16:58

标签: java mysql database login passwords

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

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

我的步骤是:

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

我很清楚,以纯文本格式存储密码是一个很大的安全漏洞,但是现在我只是试图学习在Java程序中使用数据库中数据的方式

这是我的代码:

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();
    }
}

2 个答案:

答案 0 :(得分:1)

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

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();    
}

答案 1 :(得分:0)

“如果我能够看得更远,那仅仅是因为我站在巨人的肩膀上。”

这是巨人:

https://spring.io

您会找到类似的东西:

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