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
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.First of all, use a parameterized query instead of hard-conding your parameters in your SQL:
Now if you just want to test if a rank is already in the table before you add it, you just need to check: