You are on page 1of 3

package javaapplication1;

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.sql.*;
public class JavaApplication1 {
JButton b1,b2,b3,b4,b5,b6;
JLabel l1,l2,l3;
JTextField t1,t2;
JComboBox co;
JavaApplication1()
{
JFrame f=new JFrame("jdbc");
f.setVisible(true);
f.setSize(300,400);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b1=new JButton("insert");
b2=new JButton("update");
b3=new JButton("search");
b4=new JButton("delete");
b5=new JButton("exit");
b6=new JButton("Clear");
l1=new JLabel("id");
l2=new JLabel("name");
l3=new JLabel("sex");
String s[]={"male","femal"};
co=new JComboBox(s);
t1=new JTextField(10);
t2=new JTextField(10);
JPanel p=new JPanel();
p.setLayout(new GridLayout(6,2));
p.add(l1);
p.add(t1);
p.add(l2);
p.add(t2);
p.add(l3);
p.add(co);
p.add(b1);
p.add(b2);
p.add(b3);
p.add(b4);
p.add(b5);
p.add(b6);
f.add(p);
Ho u=new Ho();
b1.addActionListener(u);
b2.addActionListener(u);
b3.addActionListener(u);
b4.addActionListener(u);
b5.addActionListener(u);
b6.addActionListener(u);
}
public static void main(String[] args) {
new JavaApplication1();
}
class Ho implements ActionListener{
public void actionPerformed(ActionEvent e) {

try{
Class.forName("com.mysql.jdbc.Driver");
Connection
c=DriverManager.getConnection("jdbc:mysql://localhost:3306/hh","root","root");
Statement st=c.createStatement();
//st.executeUpdate("create table stud(id int,name varchar(10),sex
varchar(12)");
if(e.getSource()==b1){
st.executeUpdate("insert into stud
values('"+t1.getText()+"','"+t2.getText()+"','"+co.getSelectedItem()+"')");

}
if(e.getSource()==b2){
st.executeUpdate("update stud set name='"+t2.getText()+"' where
id='"+t1.getText()+"'");
st.executeUpdate("update stud set sex='"+co.getSelectedItem()+"'where
id='"+t1.getText()+"'");

}
if(e.getSource()==b4){
st.executeUpdate(" delete from stud where id='"+t1.getText()+"'");

}
if(e.getSource()==b3){
ResultSet r=st.executeQuery("select * from stud where
id='"+t1.getText()+"'");
r.next();
t2.setText(r.getString(2));
co.setSelectedItem(r.getString(3));

}
if(e.getSource()==b5){
System.exit(0);

}
if(e.getSource()==b6){
t1.setText(null);
t2.setText(null);
co.setSelectedIndex(0);

}catch(Exception t){
t.printStackTrace();
}
}

}
}

You might also like