我正在尝试使用mySQl数据库用Java创建一个简单的登录系统。
我已将用户ID和密码存储在数据库表中。 我想出了一种登录方法,该方法似乎运行良好,但是我不确定这是否是正确的方法,因为我找不到用于登录系统的任何在线资源。
我的步骤是:
我很清楚,以纯文本格式存储密码是一个很大的安全漏洞,但是现在我只是试图学习在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();
}
}
答案 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)
“如果我能够看得更远,那仅仅是因为我站在巨人的肩膀上。”
这是巨人:
您会找到类似的东西:
Optional<User> r = userRepo.findByName(name);
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
if (passwordEncoder.matches(password, user.getPassword())) {
// ...
}