NetBeans - 按钮 select 数据库 else if

NetBeans - button select database else if

我想在netbeans中调用数据库使用按钮中的id和密码,所以我这样做了

private void loginActionPerformed(java.awt.event.ActionEvent evt) {                                      
    try {
        String sql="select *from login where ID = '"+id.getText()+"'and Password = '"+String.valueOf(pass.getPassword())+"'and Status ='"+pilih1.getSelectedItem().toString()+"'";
        ResultSet rss1=st.executeQuery(sql);
        if ((rss1.next())&&(pilih1.getSelectedItem().toString() == "Pasien")){
            pasien1 = new pasien1();
            pasien1.setVisible(true);
            this.dispose();
            System.out.println("haha");
        }
        else if ((rss1.next())&&(pilih1.getSelectedItem().toString() == "Dokter")){
            dokter1 = new dokter1();
            dokter1.setVisible(true);
            this.dispose();
        }
        else if ((rss1.next())&&(pilih1.getSelectedItem().toString() == "Staff")){
            staff1 = new staff1();
            staff1.setVisible(true);
            this.dispose();
        }
        else{
            JOptionPane.showMessageDialog(null, "Gagal Login");
        }
    }
    catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Terjadi Kesalahan");
    }

}  

这个源代码可以编译我没有错误 但是为什么这段代码只能执行 if 和 else 而不能执行 else if 给出解决方案。 . .

这里有两个主要问题:

  1. String在Java中是对象,所以需要用equals方法比较,而不是==运算符,它检查对象身份,而不是平等
  2. 调用 ResultSet.next() 将使光标前进,因此您应该在 if-else 结构之前执行此操作。在当前代码中,每次评估其中一个条件时,游标都会前进,这不是您想要的行为。

简而言之:

ResultSet rss1=st.executeQuery(sql);
boolean hasResults = rss1.next()
if (hasResults && pilih1.getSelectedItem().toString().equals("Pasien")) {
    pasien1 = new pasien1();
    pasien1.setVisible(true);
    this.dispose();
    System.out.println("haha");
}
else if (hasResults && pilih1.getSelectedItem().toString().equals("Dokter")) {
    dokter1 = new dokter1();
    dokter1.setVisible(true);
    this.dispose();
}
else if (hasResults && pilih1.getSelectedItem().toString().equals("Staff")){
    staff1 = new staff1();
    staff1.setVisible(true);
    this.dispose();
}
else{
    JOptionPane.showMessageDialog(null, "Gagal Login");
}