how to connect with dbms using a query in button of java program?
Here is an example that creates a form in java swing. When the user enters the fields and click the button, the values will get stored into the database.
import javax.swing.*; import java.awt.*; import java.io.*; import java.awt.event.*; import java.sql.*; class Form extends JFrame { JButton ADD; JPanel panel; JLabel label1,label2,label3,label4,label5; final JTextField text1,text2,text3,text4,text5; Form(){ label1 = new JLabel(); label1.setText("UserID:"); text1 = new JTextField(20); label2 = new JLabel(); label2.setText("First Name:"); text2 = new JTextField(20); label3 = new JLabel(); label3.setText("Last Name:"); text3 = new JTextField(20); label4 = new JLabel(); label4.setText("ADDRESS:"); text4 = new JTextField(20); label5 = new JLabel(); label5.setText("Email:"); text5 = new JTextField(20); ADD=new JButton("ADD"); panel=new JPanel(new GridLayout(6,2)); panel.add(label1); panel.add(text1); panel.add(label2); panel.add(text2); panel.add(label3); panel.add(text3); panel.add(label4); panel.add(text4); panel.add(label5); panel.add(text5); panel.add(ADD); add(panel,BorderLayout.CENTER); setTitle("FORM"); ADD.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae){ String value1=text1.getText(); String value2=text2.getText(); String value3=text3.getText(); String value4=text4.getText(); String value5=text5.getText(); try{ Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root" ); Statement st=conn.createStatement(); st.executeUpdate("insert into data(id,fname,lname,address,email) values('"+value1+"','"+value2+"','"+value3+"','"+value4+"','"+value5+"')"); JOptionPane.showMessageDialog(null,"Inserted Successfully!"); } catch(Exception e){} } }); } } class FormDemo { public static void main(String arg[]) { try { Form frame=new Form(); frame.setSize(300,300); frame.setVisible(true); } catch(Exception e){ } } }
Ads