我正在用 Java 编写一个小登录程序,但遇到了一个小问题:在检查用户名或密码是否与数据库中的条目匹配时,我使用 next()
迭代器,并且如果输入的数据与我的数据库中的数据不匹配,我希望它显示“用户名或密码不正确”。
问题是每次我测试它并尝试使用不正确的用户名或密码登录时,迭代器都会一一检查我的数据库条目,并在每次查询时显示“错误的用户名或密码”。我只是希望它在检查完数据库中的所有数据后立即显示消息。这是我的代码;我希望有人能帮助我...
try
{
String un=username.getText();
String pw=password.getText();
Connection conn = DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\JGUTX\\Documents\\UserDatabase.accdb");
Statement s=conn.createStatement();
ResultSet rs=s.executeQuery("SELECT UserName,Password,Administrator FROM UserDatabase");
while(rs.next()){
boolean type=rs.getBoolean("Administrator");
String dbUser=rs.getString("UserName");
String dbPass=rs.getString("Password");
if(un.equals(dbUser)&& pw.equals(dbPass)){
if(type==true){
AdMenu admenu=new AdMenu();
admenu.show();
this.setVisible(false);
} else{
Menu menu=new Menu();
menu.show();
this.setVisible(false);
}
}else{
JOptionPane.showMessageDialog(null,"Ïncorrect username or password");
}
}
}
catch (Exception e)
{
System.err.println("Got an exception!");
System.err.println(e.getMessage());
JOptionPane.showMessageDialog(null, "Error connecting to database...");
}
最佳答案
试试这个:
try
{
boolean accountMatches = false;
String un=username.getText();
String pw=password.getText();
Connection conn = DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\JGUTX\\Documents\\UserDatabase.accdb");
Statement s=conn.createStatement();
ResultSet rs=s.executeQuery("SELECT UserName,Password,Administrator FROM UserDatabase");
while(rs.next()){
boolean type=rs.getBoolean("Administrator");
String dbUser=rs.getString("UserName");
String dbPass=rs.getString("Password");
if(un.equals(dbUser)&& pw.equals(dbPass)){
accountMatches = true;
if(type==true){
AdMenu admenu=new AdMenu();
admenu.show();
this.setVisible(false);
} else{
Menu menu=new Menu();
menu.show();
this.setVisible(false);
}
}
if(accountMatches) break;
}
if(!accountMatches) JOptionPane.showMessageDialog(null,"Ïncorrect username or password");
}
catch (Exception e)
{
System.err.println("Got an exception!");
System.err.println(e.getMessage());
JOptionPane.showMessageDialog(null, "Error connecting to database...");
}
关于java - 需要java登录代码的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44572446/