如何在java中插入单选按钮值到数据库中



我有2个JRadioButtons分别叫做Male &女性在我的设计中。在源代码的最后,我声明了一个私有字符串变量,名为gender。然后在Jradiobutton action执行的事件中,我已经分配了这个,

在jradio button1操作执行事件性别= "男"

In jradio button2 action performed事件性别= "女"

在我的数据库中,我有列称为性别,所以我需要知道的是我需要插入,选择的jradiobutton值(男性或女性)进入数据库时,我点击添加按钮在我的表单。

在我的添加按钮的动作执行事件我已经做到了这一点,我不知道如何插入jradioButton值db(我需要添加它后txtname),请告诉我这样做的方式。这是我的代码

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();
        }            
    }

可以使用JRadioButton的isSelected()和getValue()方法。

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

假设已选择性别,

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

最新更新