Oracle Database Connection in GUI Application
Write the following code in a java file named "insertDemo.java"
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
public class insertData extends JFrame implements ActionListener
{
JTextField name,addr,sal;
JLabel n,a,s;
JButton ins,canc,clr;
insertData()
{
setLayout(null);
name=new JTextField(15);
addr=new JTextField(15);
sal=new JTextField(15);
n=new JLabel("Enter Employee Name :");
a=new JLabel("Enter Employee Address :");
s=new JLabel("Enter Employee Salary :");
ins=new JButton("Insert");
canc=new JButton("Close");
clr=new JButton("Clear");
add(n); add(name);
add(a); add(addr);
add(s); add(sal);
add(ins); add(canc); add(clr);
n.setBounds(10,10,130,25); name.setBounds(170,10,130,25);
a.setBounds(10,50,150,25); addr.setBounds(170,50,130,25);
s.setBounds(10,90,150,25); sal.setBounds(170,90,130,25);
ins.setBounds(20,130,80,30); canc.setBounds(110,130,80,30);
clr.setBounds(200,130,80,30);
setBounds(150,100,330,210);
getContentPane().setBackground(new Color(200,208,247));
setTitle("Insert Records...");
setVisible(true);
ins.addActionListener(this);
canc.addActionListener(this);
clr.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==ins)
{
try{
String nm=name.getText();
String ad=addr.getText();
int salry=Integer.parseInt(sal.getText());
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521","system","123456");
PreparedStatement pst=con.prepareStatement("insert into emp values(?,?,?)");
pst.setString(1,nm);
pst.setString(2,ad);
pst.setInt(3,salry);
int n= pst.executeUpdate();
//////////////////////////////////////////////////// OR /////////////////////////////////////////////////
/*
Statement st=con.createStatement();
String query="insert into emp values(' "+nm+" ' , ' "+ad+" ' , "+salry+")";
System.out.println(query);
int n= st.executeUpdate(query);
*/
if(n>0)
JOptionPane.showMessageDialog(this,"Record Inserted..");
else
JOptionPane.showMessageDialog(this,"Record Insertion Error..");
}catch(Exception ex) {}
}
else if(ae.getSource()==canc)
this.dispose();
else if(ae.getSource()==clr)
{
name.setText(""); addr.setText(""); sal.setText("");
}
}
public static void main(String arg[])
{
new insertData();
}
}
To Execute this Program you will have to set class path first....
i.e.
set classpath= .; C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar
Then Compile & run
javac insertDemo.java
java insertDemo
Output :
excellent
ReplyDelete