它使用正确的用户和密码正常工作,但是当我使用错误的用户和密码时,它不起作用。如果正常工作,则其他语句无效。
这是我的代码:
String user = textField.getText().trim();
String pwd = new String(passwordField.getPassword()).trim();
String type = (String) comboBox.getSelectedItem();
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "root");
String sql = "select * from userauthentication where username=? and password=? and type=?";
ps = con.prepareStatement(sql);
ps.setString(1, user);
ps.setString(2, pwd);
ps.setString(3, type);
rs = ps.executeQuery();
while (rs.next()) {
String uname = rs.getString("username");
String pass = rs.getString("password");
if ((user.equals(uname) && pwd.equals(pass))) {
if (type.equals(Admin_Type)) {
JOptionPane.showMessageDialog(null,
" This is from admin message.");
// rs.close();
} else if (type.equals(User_Type)) {
JOptionPane.showMessageDialog(null,
"This is from user message.");
// rs.close();
}
else {
JOptionPane.showMessageDialog(null,
"No user found!.");
}
} else {
JOptionPane.showMessageDialog(null,
"Something going wrong.please try again.");
}
}
} catch (Exception e) {
System.out.println(e);
}
答案 0 :(得分:1)
在while循环之前添加以下条件
if (!rs.isBeforeFirst() ) {
//show error message here.
System.out.println("No data");
}
答案 1 :(得分:1)
可能的解决方法是使用if语句而不是while循环来检查您是否检索了有效用户。
考虑结果集可能不会检索任何数据,因此在这种情况下,while循环之后的语句将不会被执行。
这是另一种选择
if (rs.next()) {
if (type.equals(Admin_Type)) {
message = " This is from admin message.";
} else if (type.equals(User_Type)) {
message = " This is from user message.";
} else {
message = "Invalid Type user!.";
}
} else {
message ="Something going wrong.please try again.";
}
JOptionPane.showMessageDialog(null,message);
还要考虑使用基于框架的其他身份验证方法,避免创建自己的身份验证方法。此示例适用于教育程序,以练习如何使用ResultSet从数据库中读取字段以及如何通过JOptionPane显示消息。
此致