Monday, January 13, 2014

Java JDBC programming Example 14

//Note: create  a DSN in the name of sql that is pointing the table name limbs in the database with three String column  names things,legs,arms







import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

public class Jdbc14 implements ActionListener{

JFrame fr1;
JLabel l1,l2,l3;
JTextField tf1,tf2,tf3;
JButton b1,b2;
Jdbc14() {
l1 = new JLabel("Enter Your thing ");
l2 = new JLabel("Enter no of legs ");
l3 = new JLabel("Enter no of arms ");

tf1=new JTextField(10);
tf2=new JTextField(10);
tf3=new JTextField(10);

b1 = new JButton("Submit");
b2 = new JButton("Cancel");
fr1=new JFrame("Insert");
}

public void display() {
fr1.setLayout(new FlowLayout(FlowLayout.LEFT));

fr1.add(l1);
fr1.add(tf1);

fr1.add(l2);
fr1.add(tf2);

fr1.add(l3);
fr1.add(tf3);

fr1.add(b1);
fr1.add(b2);
b1.addActionListener(this);
b2.addActionListener(this);


fr1.setSize(400,500);
fr1.setVisible(true);
fr1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

public void actionPerformed(ActionEvent e){
String s = e.getActionCommand();
if(s.equals("Submit")){
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         Connection c =  DriverManager.getConnection("jdbc:odbc:sql");
         PreparedStatement pstmt = c.prepareStatement
                                                ("insert into limbs (things,legs,arms) values (?,?,?)");
         pstmt.setString(1,tf1.getText()); //legs 8
         pstmt.setInt(2,Integer.parseInt(tf2.getText()));
         pstmt.setInt(3,Integer.parseInt(tf3.getText()));
         int i = pstmt.executeUpdate();
         pstmt.close();
         c.close();
}catch(Exception ee){}

}

if(s.equals("Cancel")){
tf1.setText("");
tf2.setText("");
tf3.setText("");
}

Post a Comment