Search code examples
javamysqlwhile-looplogical-operators

How to check for a condition within a while loop java


String valChecker = "SELECT * FROM `committee_memba` where (Rank= 'Chairperson' or Rank='Vice-Chair') and committee_name='" + jComboBox1.getSelectedItem().toString() + "'";
System.out.println(valChecker);
PreparedStatement stmt = conn.prepareStatement(valChecker);
rs = stmt.executeQuery();
while (rs.next()){
    String rnk = rs.getString("Rank");
    System.err.println(rnk);
    if ((rnk.equals("Chairperson") && rank.equals("Chairperson")) || (rnk.equals("Vice-Chair") && rank.equals("Vice-Chair"))) {
        JOptionPane.showMessageDialog(rootPane, "Your Rank, " + rank + " already Exist, please review your membership or remove "+rank+" before adding another");
    else {
        pst.setString(3, rank);
        pst.execute();
        JOptionPane.showMessageDialog(this, "Saved, OK");
    }

The Select query checks for existing rank of chairperson and vice-chair and it works well.

I want to save a new record with a chairperson or vice-chair if and only if the candidates with the said title does not exist, that is you can only have one chair or vice-chair, but my JOPtionpane is reporting well but the pst.execute() for inserting is still working, despite the JOptionpane giving the error message.


Solution

  • If someone had the problem I had, am happy to share assistance I got outside this forum, perhaps it could save someone

     String valChecker = "SELECT * FROM `committee_memba` where Rank= '"+rank+"'  and committee_name='"+ jComboBox1.getSelectedItem().toString() + "'";
               
                PreparedStatement stmt = conn.prepareStatement(valChecker);
                rs = stmt.executeQuery();
                 
                
                    
                        
                        if (rs.next() && (rank.equals("Chairperson") || rank.equals("Vice-Chair"))) {
                            
                            JOptionPane.showMessageDialog(rootPane, "Your Rank, " + rank + " already Exist, please review your membership or remove " + rank + " before adding another");
                        } else {
                            pst.setString(3, rank);
                            pst.execute();
                            JOptionPane.showMessageDialog(this, "Saved, OK");
                        }