Search code examples
javasqlsqlitewhere-clauseclause

sql WHERE clause not working properly


I am new to Java and sql. I have written a where clause however it doesn't seem to be working properly.

"SELECT Threat_Hazard_ID FROM Threats_Hazards_Categories WHERE Hazard = '" + hz + "'";

based on a selection in a previous comboBox "hz", I want to pull the ID I've given it. Yet it seems to just kick back the selection which was made.

here is the section of code I have written, fill free to offer better methods of performing this task.

comboBox.addItemListener(new ItemListener() {
    @Override
    public void itemStateChanged(ItemEvent arg0) {
        try {
            Object hz = comboBox.getSelectedItem();
            System.out.println(hz);
            c = DriverManager.getConnection("jdbc:sqlite:MAAWB.db");
            stmt = c.createStatement();
            String Hid = "SELECT Threat_Hazard_ID FROM Threats_Hazards_Categories WHERE Hazard = '" + hz + "'";
            hidtest = stmt.executeQuery(Hid);
            int test = hidtest.getInt("Threat_Hazzard_ID");
            String hazardCP = "SELECT HazardCP FROM Hazard_CP WHERE Threat_Hazard_Id = " + Hid;
            if(radioButton.isSelected() != false) {
                while(hcp.next()){
                    Hcp = hcp.getString("HazardCP");
                    comboBox_1.removeItem(Tcp);
                    comboBox_1.addItem(Hcp);

Solution

  • Change this

    String Hid = "SELECT Threat_Hazard_ID FROM Threats_Hazards_Categories WHERE Hazard = '" + hz + "'";
    

    To

    String Hid = "SELECT           Threat_Hazard_ID FROM Threats_Hazards_Categories WHERE Hazard = '" + hz.toString()+ "'";