如何在java中将单选按钮的值插入数据库?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32032012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to insert value of radio button into database in java?
提问by
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,
我在我的设计中有 2 个 JRadioButton,称为男性和女性。在源代码的末尾,我声明了一个名为性别的私有字符串变量。然后在我指定的 Jradiobutton 动作执行事件中,
In jradio button1 action performed event gender="Male"
在 jradio button1 中执行的事件性别 =“男”
In jradio button2 action performed event gender="Female"
在 jradio button2 中执行的事件性别 =“女性”
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.
在我的数据库中,我有一个名为 Gender 的列,所以我需要知道的是,当我单击表单中的“添加”按钮时,我需要将选定的 jradiobutton 值(男性或女性)插入到数据库中。
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
在我的添加按钮的动作执行事件中,我已经完成了这个,我不知道如何将 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();
}
}
采纳答案by Surya
You can use isSelected() and getValue() methods of JRadioButton.
您可以使用 JRadioButton 的 isSelected() 和 getValue() 方法。
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 + "')");
回答by Hamid
Use characters. If male was selected, insert M in DB, else F
使用字符。如果选择了男性,则在 DB 中插入 M,否则为 F