Sunday 8 September 2013

jdbc odbc program using MS-Access database

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

class Myframe extends JFrame implements ActionListener

 {

   JLabel lno,lname;
   JTextField tno,tname;
   JButton insert,view,update,search,nxt,pre,lst,frt,clr,dlt,exit;

   Connection cn;
   Statement st;
   ResultSet rs;
   Container conpane;


   Myframe()

   {

     lno=new JLabel("Eno");
     lname=new JLabel("Ename");

     tno=new JTextField(6);
     tname=new JTextField(15);

     insert=new JButton("Insert");
     view=new JButton("View");
     nxt=new JButton("Next");
     pre=new JButton("Previous");
     lst=new JButton("Last");
     frt=new JButton("First");
     clr=new JButton("Clear");
     dlt=new JButton("Delete");
     update=new JButton("Update");
     search=new JButton("Search");
     exit=new JButton("Exit");

     conpane = getContentPane();

     JPanel txtPanel,btnPanel;

    txtPanel = new JPanel();
    btnPanel = new JPanel();
     //setLayout(new GridLayout(2,2));
        conpane.add(txtPanel,BorderLayout.NORTH);
        conpane.add(btnPanel,BorderLayout.CENTER);
     txtPanel.add(lno);
     txtPanel.add(tno);

     txtPanel.add(lname);
     txtPanel.add(tname);

     btnPanel.add(insert);
     btnPanel.add(view);
     btnPanel.add(nxt);
     btnPanel.add(pre);
     btnPanel.add(lst);
     btnPanel.add(frt);
     btnPanel.add(clr);
     btnPanel.add(dlt);
     btnPanel.add(update);
     btnPanel.add(search);
     btnPanel.add(exit);

     insert.addActionListener(this);
     view.addActionListener(this);
     nxt.addActionListener(this);
     pre.addActionListener(this);
     lst.addActionListener(this);
     frt.addActionListener(this);
     clr.addActionListener(this);
     dlt.addActionListener(this);
     update.addActionListener(this);
     search.addActionListener(this);
     exit.addActionListener(this);

     try
                     {


                      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");


                      cn=DriverManager.getConnection("jdbc:odbc:employeedsn");
                      st=cn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
                     rs=st.executeQuery("select * from emp");
                     rs.next();

                }catch(Exception e){}


    }

    public void actionPerformed(ActionEvent a)

    {

    try
      {


         if(a.getSource()==search)
           {

            dbOpen();
             String str = JOptionPane.showInputDialog(null, "Enter empno : ");

            rs=st.executeQuery("select * from emp where eno="+str+"");

            rs.next();
            setText();
           }

         if(a.getSource()==update)
           {

             dbOpen();
             int ueno=Integer.parseInt(tno.getText());
             String uname=(tname.getText());


             st.executeUpdate("UPDATE emp SET eno=" + ueno +",ename='" + tname.getText() + "' WHERE eno="+ ueno +"  ");
             JOptionPane.showMessageDialog(null,"Record is updated");

           }


         if(a.getSource()==dlt)
            {
               int deno=Integer.parseInt(tno.getText());

               st.executeUpdate("DELETE FROM emp WHERE eno="+ deno);
               JOptionPane.showMessageDialog(null,"Record is deleted");

            dbClose();
            dbOpen();

            }



         if(a.getSource()==clr)
           {
                   tno.setText("");
                   tname.setText("");
                   rs.first();
           }


         if(a.getSource()==frt)
          {
                  rs.first();
                  setText();
           }


         if(a.getSource()==lst)
          {
                 rs.last();
                  setText();
            }

         if(a.getSource()==nxt)
          {

             if(!rs.isAfterLast())
              {

                 rs.next();
                 setText();

            }

          else
             {
                  JOptionPane.showMessageDialog(null,"Last Record");
                 rs.previous();
             }

           }


         if(a.getSource()==pre)
          {

            if(!rs.isBeforeFirst())
              {

                 rs.previous();
                 setText();

                 }

           else
            {
                 JOptionPane.showMessageDialog(null,"First Record");
                 rs.first();
            }

          }


        if(a.getSource()==insert)
        {
          int eno=Integer.parseInt(tno.getText());
          String name=(tname.getText());


         st.executeUpdate("insert into emp values("+eno+",'"+name+"')");
         JOptionPane.showMessageDialog(null,"Record inserted into database");

         dbClose();
            dbOpen();

        }



       if(a.getSource()==view)

       {

            rs.next();
            setText();
            dbClose();
            dbOpen();

       }

       if(a.getSource()==exit)
                   {
                       if(JOptionPane.showConfirmDialog(null,"Are You Sure You Want to Exit?","Confirm",JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION)
                       System.exit(0);
                }



    }catch(Exception e)
      {
      }

}



public void dbOpen()
    {
        try
                {


                 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");


                 cn=DriverManager.getConnection("jdbc:odbc:employeedsn");
                 st=cn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
                rs=st.executeQuery("select * from emp");
                rs.next();

                }catch(Exception e){}
    }


public void setText(){
        try{
            tno.setText(rs.getString(1));
            tname.setText(rs.getString(2));
            }catch(Exception ex){}
            }


            public void dbClose()
                {
                    try{
                        st.close();
                    rs.close();
                    cn.close();
                    }catch(Exception e){}
    }

}

class jdbcdemoframe
{
    public static void  main(String s[])
    {
        Myframe f= new Myframe();
        f.setVisible(true);
        f.setTitle("Employee Information");
        f.setSize(350,250);
    }
}

java button applet program

import java.awt.*;
public class ButtonActionsTest extends java.applet.Applet {

public void init() {


setBackground(Color.white);
add(new Button("Red"));
add(new Button("Blue"));
add(new Button("Green"));
add(new Button("White"));
add(new Button("Black"));


}
public boolean action(Event evt, Object arg) {
if (evt.target instanceof Button)
changeColor((String)arg);
return true;
}
void changeColor(String bname) {
if (bname.equals("Red")) setBackground(Color.red);
else if (bname.equals("Blue")) setBackground(Color.blue);
else if (bname.equals("Green")) setBackground(Color.green);
else if (bname.equals("White")) setBackground(Color.white);
else setBackground(Color.black);
}
}

color box in java

import java.awt.Graphics;
 import java.awt.Color;

 public class ColorBoxes extends java.applet.Applet {

public void paint(Graphics g) {
 int rval, gval, bval;

 for (int j = 30; j < (this.size().height -25); j += 30)
 for (int i = 5; i < (this.size().width -25); i+= 30) {
 rval = (int)Math.floor(Math.random() * 256);
 gval = (int)Math.floor(Math.random() * 256);
 bval = (int)Math.floor(Math.random() * 256);

 g.setColor(new Color(rval,gval,bval));
 g.fillRect(i,j,25,25);
 g.setColor(Color.black);
 g.drawRect(i-1,j-1,25,25);
 }
 }
 }

color test in java

import java.awt.*;
public class ColorTest extends java.applet.Applet {
ColorControls RGBcontrols, HSBcontrols;
Canvas swatch;
public void init() {
Color theColor = new Color(0,0,0);
float[] HSB = Color.RGBtoHSB(theColor.getRed(),
theColor.getGreen(), theColor.getBlue(),
(new float[3]));
setLayout(new GridLayout(1,3,10,10));
// The color swatch
swatch = new Canvas();
swatch.setBackground(theColor);
// the control panels
RGBcontrols = new ColorControls(this,"Red", "Green", "Blue",theColor.getRed(), theColor.getGreen(),theColor.getBlue());
HSBcontrols = new ColorControls(this,"Hue", "Saturation", "Brightness",(int)(HSB[0] * 360), (int)(HSB[1] * 100),(int)(HSB[2] * 100));
add(swatch);
add(RGBcontrols);
add(HSBcontrols);
}
public Insets insets() {
return new Insets(10,10,10,10);
}
void update(ColorControls in) {
Color c;
String v1 = in.f1.getText();
String v2 = in.f2.getText();
String v3 = in.f3.getText();
if (in == RGBcontrols) { // change to RGB
c = new Color(Integer.parseInt(v1),
Integer.parseInt(v2),
Integer.parseInt(v3));
swatch.setBackground(c);

float[] HSB = Color.RGBtoHSB(c.getRed(),c.getGreen(),
c.getBlue(), (new float[3]));
HSB[0] *= 360;
HSB[1] *= 100;
HSB[2] *= 100;
HSBcontrols.f1.setText(String.valueOf((int)HSB[0]));
HSBcontrols.f2.setText(String.valueOf((int)HSB[1]));
HSBcontrols.f3.setText(String.valueOf((int)HSB[2]));
}
else { // change to HSB
int f1 = Integer.parseInt(v1);
int f2 = Integer.parseInt(v2);
int f3 = Integer.parseInt(v3);
c = Color.getHSBColor((float)f1 / 360,
(float)f2 / 100, (float)f3/100);
swatch.setBackground(c);
RGBcontrols.f1.setText(String.valueOf(c.getRed()));
RGBcontrols.f2.setText(String.valueOf(
c.getGreen()));
RGBcontrols.f3.setText(String.valueOf(c.getBlue()));
}
}
}
class ColorControls extends Panel {
TextField f1, f2, f3;
ColorTest outerparent;
ColorControls(ColorTest target,
String l1, String l2, String l3,
int v1, int v2, int v3) {
this.outerparent = target;
setLayout(new GridLayout(3,4,10,10));
f1 = new TextField(String.valueOf(v1),10);
f2 = new TextField(String.valueOf(v2),10);
f3 = new TextField(String.valueOf(v3),10);
add(new Label(l1, Label.RIGHT));
add(f1);
add(new Label(l2, Label.RIGHT));
add(f2);
add(new Label(l3, Label.RIGHT));
add(f3);
}
public Insets insets() {
return new Insets(10,10,0,0);
}
public boolean action(Event evt, Object arg) {
if (evt.target instanceof TextField) {

this.outerparent.update(this);

// retrue true;
}
// else return false;

}
}

java swing program for displaying a label

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

/* <applet code="JLabelDemo" width=355 height=200>
</applet>
*/

public class JLabelDemo extends JApplet{

public void init() {
// Get content pane
Container contentPane = getContentPane();

// Create an icon
ImageIcon ii = new ImageIcon("sateesh.jpg");

// Create a label
JLabel jl = new JLabel ("SATEESH.BAGADHI", ii, JLabel.CENTER);

// Add label to the content pane
contentPane.add(jl);
}
}

java program to convert a string from lower case to upper case

import java.lang.*;
import java.io.*;
public class key
{
public static void main(String args[])throws IOException
{
try
{
   BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
   System.out.println("enter the input from the key board");
   String str=br.readLine();
   System.out.println("Data enterd is "+str.toUpperCase());
   }
   catch(Exception e)
   {
   System.out.println(e);
   }
   }
   }

odbc jdbc program for faculty oracle table

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

public class Lab7 extends JFrame implements ActionListener
{
JLabel l1,l2,l3;
JTextField t1,t2,t3;
JButton b1,b2,b3;

Lab7()
        {
        super("DataBases");
        setSize(500,450);
        setResizable(false);
        setLayout(null);


        l1=new JLabel("Name           :");
        l2=new JLabel("Department :");
        l3=new JLabel("Experience  :");

        t1=new JTextField(20);
        t2=new JTextField(20);
        t3=new JTextField(20);
       
        b1=new JButton("Next");       
        b2=new JButton("Prev");
        b3=new JButton("Close");
       
       add(l1).setBounds(10,60,150,20);
       add(t1).setBounds(150,60,200,20);
  
      add(l2).setBounds(10,90,150,20);
      add(t2).setBounds(150,90,200,20);
 




 
  add(l3).setBounds(10,110,150,20);
  add(t3).setBounds(150,130,200,20);

   b1.setMnemonic('N');
   b2.setMnemonic('P');
   b3.setMnemonic('x');               
  
       add(b1).setBounds(100,180,120,20);       
  add(b2).setBounds(240,180,120,20);      
  add(b3).setBounds(380,180,120,20);

   b1.addActionListener(this);   
   b2.addActionListener(this);
   b3.addActionListener(this);
       
  addWindowListener(new WindowAdapter(){public void  windowClosing(WindowEvent e){System.exit(0);}});
   }

public void actionPerformed(ActionEvent ae)
        {   
try
    {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");     
   Connection   dbcon=DriverManager.getConnection ("jdbc:odbc:ram","scott","tiger");
   
 String query="select  name,dept,exp   from   faculty";
     Statement stmt=dbcon.createStatement();
     ResultSet rs=stmt.executeQuery(query);
   
     if(ae.getSource()==b1)
        {
            rs.next();
            t1.setText(rs.getString("name"));
            t2.setText(rs.getString("dept"));
            t3.setText(rs.getString("exp"));
        }
   
if(ae.getSource()==b2)
        {
            rs.previous();
            t1.setText(rs.getString("name"));
            t2.setText(rs.getString("dept"));
            t3.setText(rs.getString("exp"));
        }


     if(ae.getSource()==b3)
{
            System.exit(0);
        }
    }
    catch(ClassNotFoundException e)
    {
    System.out.println(e);
    }
    catch(Exception e)
    {
    System.out.println(e);
    }
        }

public static void main(String str[])
        {
        Lab7  l=new Lab7();
        l.setVisible(true);
        }

}

java applet displaying name

import java.awt.Graphics;
 import java.awt.Font;
 import java.awt.Color;

 public class MoreHelloApplet extends java.applet.Applet {

 Font f = new Font("TimesRoman",Font.BOLD,36);
 String name;

 public void init() {
 this.name = getParameter("name");
 if (this.name == null)
this.name = "Sateesh Bagadhi";

 this.name = "Hello  " + this.name + "!";
    }

 public void paint(Graphics g) {
 g.setFont(f);
 g.setColor(Color.red);
 g.drawString(this.name, 5, 50);
 }
 }

java program for student details

import java.io.*;

class Student{

public static void main(String args[]){

    InputStreamReader is = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(is);
   
    System.out.print("Welcome to java");
   
    try{
   
        System.out.println("Enter Student Name:");
       
        String Name = br.readLine();
       
        System.out.println("Enter Student Number:");
       
        String No = br.readLine();
       
        System.out.println("Enter Student class:");
       
        String Clas = br.readLine();
   
    System.out.println(" Hi "+Name +" your no is: "+ No +", you are studying "+Clas +"!");
        }
       
    catch (IOException Err) {
   
    System.out.print("Error in reading Line!");
    }
   
    catch(NumberFormatException Err){
    System.out.print("Error in Number format conversion!");
    }

    }
}

java program- Vowels And Consonants

public class VowelsAndConsonants {
  public static void main(String[] args) {
    for(int i = 0; i < 100; i++) {
      char c = (char)(Math.random() * 26 + 'a');
      System.out.print(c + ": ");
      switch(c) {
      case 'a':
      case 'e':
      case 'i':
      case 'o':
      case 'u':
                System.out.println("vowel");
                break;
      case 'y':
      case 'w':
                System.out.println(
                  "Sometimes a vowel");
                break;
      default:
                System.out.println("consonant");
      }
    }
  }
}

switch case demo

class SwitchDemo
{
public static void main(String args[])
{
 int month=Integer.parseInt(args[0]);
switch(month)
{

case 1: System.out.println("January");break;

case 2: System.out.println("February");break;

case 3: System.out.println("March");break;

case 4: System.out.println("April");break;

case 5: System.out.println("May");break;

case 6: System.out.println("June");break;

case 7: System.out.println("July");break;

case 8: System.out.println("August");break;

case 9: System.out.println("September");break;

case 10: System.out.println("October"); break;

case 11: System.out.println("November"); break;

case 12: System.out.println("October"); break;

default: System.out.println("Sorry ! invallied choice");break;

}
}
}

copying data from one array to another array

public class CopyArray {
    public static void main(String[] args) {
        int array1[]= {2,3,4,5,8,9};
        int array2[] = new int[6];
        System.out.println("array:");
        System.out.print("[");
        for (int i=0; i<array1.length; i++){
            System.out.print(" "+array1[i]);
        }
        System.out.print("]");
        System.out.println("\narray1:");
        System.out.print("[");
        for(int j=0; j<array1.length; j++){
            array2[j] = array1[j];
            System.out.print(" "+ array2[j]);
        }
        System.out.print("]");
    }
}

Array program in java

import java.util.*;

public class  ArrayDemo{
  public static void main(String[] args){
  int num[] = {50,20,45,82,25,63};
  int l = num.length;
  int i,j,t;
  System.out.print("Given number : ");
  for (i = 0;i < l;i++ ){
  System.out.print("  " + num[i]);
  }
  System.out.println("\n");
  System.out.print("Accending order number : ");
  Arrays.sort(num);
    for(i = 0;i < l;i++){
  System.out.print("  " + num[i]);
  }
  }
}

Break And Continue operators in java


public class BreakAndContinue {

  public static void main(String[] args) {
  
 for(int i = 0; i < 100; i++) {
      if(i == 74) break; // Out of for loop
      if(i % 9 != 0) continue; // Next iteration
      System.out.println(i);
    }
    int i = 0;
    // An "infinite loop":
    while(true) {
      i++;
      int j = i * 27;
      if(j == 1269) break; // Out of loop
      if(i % 10 != 0) continue; // Top of loop
      System.out.println(i);
    }
  }
}

Conditional operator ?: (Ternary operator)

class BigNo
{
     public static void main (String args[])
    {

          int a = Integer.parseInt(args[0]);

          int b = Integer.parseInt(args[1]);

          int c = Integer.parseInt(args[2]);

          int x = (a>b)?(a>c?a:c):(b>c?b:c);

          System.out.println(+x);
      }
}

Reading values through keyboard using Scanner


import java.util.*;

public class Array
{
       public static void main(String args[])
      {

         int[] a=new int[6];

         Scanner sc=new Scanner(System.in);
         System.out.println("Please enter elements...");
         for(int j=0;j<6;j++)
         a[j]=sc.nextInt();
         System.out.println("Array elements are : ");
         for (int i=0;i<a.length;i++)
         System.out.println(a[i]);
       }
}