skip to Main Content
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.

2

Answers


  1. If you do not wish to utilize a flag, abstract into a boolean method, and use the return statement to exit from the first condition.

    Alternatively, you could use JOptionPane.showConfirmMessageDialog(rootPane, "Your Rank, " + rank + " already Exist, please review your membership or remove "+rank+" before adding another", JOptionPane.YES_NO_CANCEL_OPTION) which will interrupt.

    Login or Signup to reply.
  2. First of all, use a parameterized query instead of hard-conding your parameters in your SQL:

    String valChecker = "SELECT * FROM `committee_memba` where Rank= ? and 
     committee_name=?";
    PreparedStatement stmt = conn.prepareStatement(valChecker);
    stmt.setString(1, rank);
    stmt.setString(2, jComboBox1.getSelectedItem().toString());
    rs = stmt.executeQuery();
    

    Now if you just want to test if a rank is already in the table before you add it, you just need to check:

    boolean exists = rs.next();
    stmt.close();
    
    if (exists) {
        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");}
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search