gpt4 book ai didi

java - 如何在 Java-mysql 中验证用户名和密码?

转载 作者:搜寻专家 更新时间:2023-11-01 02:49:07 24 4
gpt4 key购买 nike

如何以最正确的方式验证用户输入数据库的用户名和密码?

In c++, we used to verify by using if-else:
if((user == "username")&&(pass == "password")){
cout<<"You are now logon!";
}

在 java-mysql 中我不确定我是否在正确的轨道上:

登录按钮

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:

user = jTextField1.getText();
pass = jPasswordField1.getPassword();
login();
}

方法/函数

private void login() {

try {
if (user != null) {
sql = "Select * from users_table Where username='" + user + "'";
rs = stmt.executeQuery(sql);

rs.next();
username = rs.getString("username");
password = rs.getString("password");

}
}
catch (SQLException err) {
JOptionPane.showMessageDialog(this, err.getMessage());
}

}

如果用户输入的用户名和密码与数据库中的匹配,那么他将被引导到一个新的 jFrame else将弹出消息对话框,提示用户名或密码无效。有人可以帮我处理我的代码吗,我不知道如何在 mysql 中使用 if-else 语句;

谢谢! :)

最佳答案

执行下面的代码:

private void login() {
try {
if (user != null && pass != null) {
String sql = "Select * from users_table Where username='" + user + "' and password='" + pass + "'";
rs = stmt.executeQuery(sql);
if (rs.next()) {
//in this case enter when at least one result comes it means user is valid
} else {
//in this case enter when result size is zero it means user is invalid
}
}

// You can also validate user by result size if its comes zero user is invalid else user is valid

} catch (SQLException err) {
JOptionPane.showMessageDialog(this, err.getMessage());
}

}

关于java - 如何在 Java-mysql 中验证用户名和密码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14995873/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com