How To Use A RadioButton With MySQL Database In Java NetBeans
In this Java Tutorial we will see How To Use A jRadioButton Control With MySQL Database To:
- get value from the selected redio button and insert it into database .
- get value from mysql and select the specific radio button.
Using Java Programming Language In NetBeans Editor And MySQL Database.
- get value from the selected redio button and insert it into database .
- get value from mysql and select the specific radio button.
Using Java Programming Language In NetBeans Editor And MySQL Database.
PART1
PART2
Project Source Code:
// create a buttongroup and add our radioButtons to this group
// to do that add this code below "initComponents();"
ButtonGroup bgr = new ButtonGroup();
bgr.add(jRadioButton_JAVA);
bgr.add(jRadioButton_CSHARP);
bgr.add(jRadioButton_NONE);
bgr.add(jRadioButton_VBNET);
// create a function to connect with mysql database
public static Connection getConnection()
{
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
return con;
}
// button insert into mysql
private void jButtonInsertActionPerformed(java.awt.event.ActionEvent evt) {
Connection con = getConnection();
PreparedStatement ps;
String username = jTextFieldUsername.getText();
String lang;
if(jRadioButton_VBNET.isSelected())
{
// or
// lang = jRadioButton_VBNET.getText()
lang = "VB.NET";
}
else if(jRadioButton_CSHARP.isSelected())
{
lang = "C#";
}
else if(jRadioButton_JAVA.isSelected())
{
lang = "JAVA";
}
else
{
// the dafault value
lang = "NONE";
}
try{
ps = con.prepareStatement("INSERT INTO users(username,lang) VALUES(?,?)");
ps.setString(1, username);
ps.setString(2, lang);
if(ps.executeUpdate() > 0)
{
JOptionPane.showMessageDialog(null, "New User Added");
}else
{
JOptionPane.showMessageDialog(null, "ERROR");
}
}catch(Exception ex){
System.out.println(ex.getMessage());
}
}
// button search
private void jButtonFindActionPerformed(java.awt.event.ActionEvent evt) {
Connection con = getConnection();
PreparedStatement ps;
ResultSet rs;
try {
ps = con.prepareStatement("SELECT * FROM users WHERE id = ?");
ps.setInt(1, Integer.valueOf(jTextFieldID.getText()));
rs = ps.executeQuery();
while(rs.next()){
jTextFieldUsername.setText(rs.getString(2));
if(rs.getString(3).equals("JAVA"))
{
jRadioButton_JAVA.setSelected(true);
}
else if(rs.getString(3).equals("C#"))
{
jRadioButton_CSHARP.setSelected(true);
}
else if(rs.getString(3).equals("VB.NET"))
{
jRadioButton_VBNET.setSelected(true);
}
else
{
// the dafault value
jRadioButton_NONE.setSelected(true);
}
}
} catch (SQLException ex) {
Logger.getLogger(RadioButton_And_MySQL.class.getName()).log(Level.SEVERE, null, ex);
}
}
OutPut:
Download Projects Source Code
1 comments:
commentspk ar
Reply