Search code examples
javajdbcnetbeans-8jradiobutton

How to insert value of radio button into database in java?


i have 2 JRadioButtons called Male & Female in my design.and at the end of source code,I declared a private String variable called gender.then in in Jradiobutton action perfomed events i have assigned as this,

In jradio button1 action performed event gender="Male"

In jradio button2 action performed event gender="Female"

in my database i have column called Gender,so what i need to know is i need to insert ,selected jradiobutton value(male or Female) into database when i click Add button in my form.

In my Add button's action Performed event I have done this ,I don't know how to insert jradioButton value to db(i need to add it after txtname),Please tell me a way of doing that.this is my code

private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {                                       
    try {
        int x = JOptionPane.showConfirmDialog(null,
                    "Do You Want to add this Record?");
        if (x == 0) {
            Connection c = DBconnect.connect();
            Statement s = (Statement) c.createStatement();
            s.executeUpdate("INSERT into employee VALUES('"
                + txtEmpId.getText() + "','" + txtName.getText()+"')");        
        } catch (Exception e) {
            e.printStackTrace();
        }            
    }

Solution

  • You can use isSelected() and getValue() methods of JRadioButton.

    if(rdbGenderM.isSelected()) 
            gender="Male";
    else if(rdbGenderF.isSelected()) 
            gender="Female";
    

    Assuming gender has been selected,

    s.executeUpdate("INSERT into employee VALUES('"
                    + txtEmpId.getText() + "','" + txtName.getText() + "','" + gender + "')");