# Learn :: USING JDBC(with ACCESS), AWT, & SWING in JAVA(JDK 1.5)



## imdbest (Jul 11, 2006)

Its an live example of USING JDBC(with ACCESS), AWT, & SWING in JAVA(JDK 1.5)

This tutorial is from site currently under construction, but tuorial is accessible at THIS LINK

A Personal telephone directory using JDBC, GUI imported from Advanced Window Toolkits, SWING, etc using ACCESS database.

It allows the USER to 

    *  add new Name & Telephone Nos.
    * browse existing Names & Telephone Nos. 
    * modify exising Names/Telephone Nos.
    * delete existing Records
    * Clear the Text Fields
    * Add more than one Phone No. for a single Name Record
    * Search the first name starting from a string starting from a string
      by pressing enter.

RUNTIME IMAGE


-=-=-=-=-=-=-=-=-=-=-teledir.mdb-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
*
In Access create a DATABASE named 'TeleDir.mdb'

Here, create a Table named 'dir1'

In this table make two fields of String type

- PhoneN             ,&                   - UserName

You may enter few values here also. 



Copy this Database file in the same folder where you gonna
    create the 'TelephoneDir.java' file.
*
-=-=-=-=-=-=-=-=-=-= DATABSE-----ENDS-=-=-=-=-=-=-=-=-=-=-

NOTE : code is case SENSITIVE 

NOTE: In COdDE here the line 
con = DriverManager.getConnection ("jdb.............
the .... jdbcdbcriver={Mic ....     is for  .... jdbc: odbc: Driver={Mic ....    without space in between ': o' & ': D'

-=-=-=-=-=-=-=-=-=-=-TelephoneDir.java-=-=-=-=-=-=-=-=-=-=-=-
*


import java.awt.*;            
    import java.awt.event.*;       

import java.awt.FlowLayout;   

import java.sql.*;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.JTextField;

import javax.swing.JTextArea;

import javax.swing.JButton;

import javax.swing.JLabel;

public class TelephoneDir extends JFrame implements ActionListener
{
static JLabel label1,label2,label3,sep;
static JButton addB,modify,delete,clear,browse;
static JTextField txtA1;
static JTextArea  txtA2;
static Connection con;
static Statement st1,st2;
static ResultSet rs1;
static TelephoneDir phoneDir;

public TelephoneDir()
   {
     super("ABK Telephone Directory :");
     //JPanel TD = new JPanel();
     setLayout(new FlowLayout());
     try    {
          Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
           con = DriverManager.getConnection ("jdbcdbcriver={Microsoft Access Driver (*.mdb)};DBQ=teledir.mdb;DriverID=22}","","");//;READONLY=true",User,Password
           st1=con.createStatement();
         rs1=st1.executeQuery("select * from dir1");
        }
    catch(Exception e)
        {
         System.out.println("there was some error in establishing connection : "+e);
        }
    label1 = new JLabel("        Name :       ");
    add(label1);
    txtA1 = new JTextField(15);
    add(txtA1);
    label2 = new JLabel("  Phone Number : ");
    add(label2);
    txtA2 = new JTextArea(1,15);
    add(txtA2);
    sep = new JLabel("-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-");
    add(sep);
    addB=new JButton("ADD RECORD");
    add(addB);
    browse=new JButton("VIEW RECORDS");
    add(browse);
    modify=new JButton("MODIFY");
    add(modify);
    delete=new JButton("DELETE");
    add(delete);
    clear=new JButton("CLEAR TEXT");
    add(clear);
    sep = new JLabel("-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-");
    add(sep);
    label3 = new JLabel("");
    add(label3);
    sep = new JLabel("-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-");
    add(sep);

    addB.addActionListener(this);
    browse.addActionListener(this);
    modify.addActionListener(this);
    delete.addActionListener(this);
    clear.addActionListener(this);
    txtA1.addActionListener(this);
   }
 public void actionPerformed(ActionEvent e)
     {
         if(e.getSource()==txtA1)
          {
              label3.setText("First Name with it");
              String nam=txtA1.getText();
              try
                {

                    st1.close();                //rs1.close();
                    st1=con.createStatement();
                    rs1=st1.executeQuery("Select * from dir1 where UserName Like '"+nam+"%'");
                    rs1.next();
                    txtA2.setText(rs1.getString("PhoneN"));
                    txtA1.setText(rs1.getString("UserName"));
                }
            catch(Exception e2)
                {
                 label3.setText("No Such UserName Found : "+nam);
                }

          }
         if(e.getSource()==addB)
          {
              label3.setText("Added new RECORD to the DataBase");
              String nam=txtA1.getText();
            String num=txtA2.getText();
            try
             {
                st2=con.createStatement();
                String query="insert into dir1 values('"+num+"','"+nam+"')";
                st2.executeUpdate(query);
                st2.close();
             }
            catch(Exception e2)
             {
                label3.setText("Check that fields are not empty.");
             }

          }
         if(e.getSource()==browse)
          {
              label3.setText("View NEXT RECORD from the DataBase");
              try
                {
                if(rs1.next()==true)
                    {
                    txtA2.setText(rs1.getString("PhoneN"));
                    txtA1.setText(rs1.getString("UserName"));
                    }
                else
                    {
                    st1.close();                //rs1.close();
                    st1=con.createStatement();
                    rs1=st1.executeQuery("Select * from dir1");
                    rs1.next();
                    txtA2.setText(rs1.getString("PhoneN"));
                    txtA1.setText(rs1.getString("UserName"));
                    }
                }
            catch(Exception e2)
                {
                 label3.setText("Error in Viewing : "+e2);
                }
          }
         if(e.getSource()==modify)
          {
              label3.setText("Modify RECORD of the DataBase");
              try
                {
                st2=con.createStatement();
                String nam=txtA1.getText();
                String num=txtA2.getText();
                String ss="update dir1 set PhoneN='"+num+"', UserName='"+nam+"' where UserName='"+nam+"' OR PhoneN='"+num+"'";
                st2.executeUpdate(ss);
                st2.close();
                }
            catch(Exception e2)
                {
                label3.setText("Error in MODIFY : "+e2);
                }
          }
         if(e.getSource()==delete)
          {
              label3.setText("Delete RECORD from the DataBase");
              try
                {
                st2=con.createStatement();
                String ts=txtA1.getText();
                String ss="delete from dir1 where UserName='"+ts+"'";
                label3.setText(label3.getText() + " : " +ss);
                st2.executeUpdate(ss);
                st2.close();
                }
            catch(Exception e2)
                {
                label3.setText("Error in DELETE : "+e2);
                }
          }
         if(e.getSource()==clear)
          {
              label3.setText("Clears both of Text Fields");
              txtA1.setText("");
            txtA2.setText("");

          }
     } 
 public static void main(String args[])
   {
       TelephoneDir TAPP = new TelephoneDir();
       TAPP.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       TAPP.setSize(250,320);
       TAPP.setVisible(true);      
   }

} 


*
-=-=-=-=-=-=-=-=-=-CODE-----ENDS-=-=-=-=-=-=-=-=-=-=-=-=-



> EXPLAINATION



'import' comaand has ben used to include the needed source files in program. AWT & its preceding two are included for the graphical environment, event listening & form layout.  SQL is imported for JDBC functions i.e. for prforming the required database functions. The SWING resources are included all to add Frame, Graphical Panel, TextField, Text Area, Command Button, & Label resp. to the Form.



Here the name of class containing 'main' function is the name of file also.

So class named TelephoneDir with same case is started



(NOTE : JAVA IS CASE SENSITIVE). 



Here, in starting 8 lines with keyword static declares resp. : 
->Labels  & Button  
               (for GUI) 
->TextField & TextArea
          (for Input/Output) 
->Connection 
      (establish Databse
      connection via JDBC) ->Statement 
        (to query-update)
->ResultSet 
       (to store query res) 
->an object of class itself



Then the CONSTRUCTOR starts, here  firstly an instance is created of form & a title text is passed to it. Then FlowLayout is set for it. 



Then the CONNECTION is being established with ACCESS using Exception Handling to manage any problem with Database or Database Drivers.



Then starts the creation of instances of GUI objects i.e. Labels, TextFields & Buttons  & providing them initial values using 'new' method. Then adding them to Java Panel using 'add' method.



Here buttons have been created for mainly 5 functions:

->Adding a new Telep.
        Number  with its
        Name.

->Viewing Records
       (already added) one 
        by one in order.

->Modify the current 
        visible record
        (name/phone any)

->Delete the currently
        visible Telephone
        Record.

->Clearing TextFields,
        so if user wanna
        change rec. .



A TextField added for UserName, so only 1 Name per record can be added.

But a TEXTAREA for Phone Number allows USER to add more than 1 telephone number for the same name. 



A special label has been created at base of form like status bar showing the summary of action performed, also displaying any error occured.



ActionListener have been added to all buttons to invoke needed function at their click event.



ActionListener has also been added to TextField of User Name, to invoke the method of searching first namestarting from the written characters in field after which User Pressed ENTER to search to quick view.



Then after Constructor starts the  method 'actionPerformed' i.e. invoked each time action is being performed on any object implementing actionListener.

Here in 'if' condition using the 'getSource' method its identified that on which object the action has been performed, & then the codes needed to be executed at that action are executed.

Here, all the 5 buttons & 1 TextField is checked for action being performed, & inside the condition boundaries the required codes have been written.



Here, for TextField simple 'SELECT LIKE ..%' query has been executed to search the record & then dispalyed.

Add Button has been coded for simple 'INSERT INTO dir1..' update query.

Browse Button has been coded for simple 'RecordeSet NEXT' statement.  And checked if reached the table's end, in that case restarted from database beginning.

Modify Button has been coded for 'UPDATE dir1 SET...' statement executing update.

Delete Button execute the code 'DELETE from dir1...' statement.

Clear Button has been coded to simple set text field's value to NULL.



THEN comes the 'public static void main ( String args[])' that executes the whole program.

Here, an object TAPP has been created of the CLASS, its EXIT operation is specified. Dimensions of the FORM are described. And lastly the FORM's visibility is set to TRUE.



Now, to compile the PROGRAM you need to run command 

'javac TelephoneDir.java'

Then when its compiled successfully & its class file is made, its execute as

'java TelephoneDir'



This brings a Form, with clearly understandable  GUI.


----------



## ~Phenom~ (Jul 11, 2006)

well thanx , but I already know that.
I am doing advance java.
Still , nice tut.
If u can , please help my problem written here :

*www.thinkdigit.com/forum/showthread.php?t=31611&highlight=help+me+eat+this+cookie


----------

