Showing posts with label J2SE Database. Show all posts
Showing posts with label J2SE Database. Show all posts

Tuesday, October 18, 2011

Retrieve Data From Database and Display Using JComboBox

Program Description:

The Java Program below is similar to the topic I created about retrieving data from database and display using JList, the only difference is that this program is using JComboBox instead of JList to display the retrieved data from MS Access Database. See "Important Part of the Program" below to compare and understand the whole java program easily.


Output:
Code:

/**
 * File: retrieveDBUsingJCB.java
 * Tiltle: Retrieve Data From Database and Display Using JComboBox
 * Author: http://java-program-sample.blogspot.com/
 */

//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

public class retrieveDBUsingJCB extends JFrame {
 
 //Initializing program components
 private JButton buttons[];
 private JComboBox listBox;
 private JPanel p1,p2;
 private String bLabel[] = {"ID","First Name","Middle Name","Last Name","Age"};
 
 Connection con;
 Statement st;
 ResultSet rs;
 String db;

 //Setting up GUI
    public retrieveDBUsingJCB() {
     
     //Setting up the Title of the Window
     super("Retrieve DB and Display Using JComboBox");

     //Set Size of the Window (WIDTH, HEIGHT)
     setSize(300,200);

     //Exit Property of the Window
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          
     //Constructing JButtons and JComboBox
     buttons = new JButton[5];
     listBox = new JComboBox();
     
     //Setting up JComboBox property
     listBox.setMaximumRowCount(5);
  
  //Constructing JPanel 1 and its property
  p1 = new JPanel();
  p1.setBorder(BorderFactory.createTitledBorder("Database: "));
  p1.add(listBox); //Adding JComboBox in JPanel 1
  
  //Constructing JPanel 2 and its property
  p2 = new JPanel();
  p2.setLayout(new GridLayout(5,1));
  p2.setBorder(BorderFactory.createTitledBorder("Display: "));
  
  //Constructing all 5 JButtons using "for loop" and add it in JPanel 2
  for(int count=0; count<buttons.length; count++) {
   buttons[count] = new JButton(bLabel[count]);
   p2.add(buttons[count]);
  }
  
  //Setting up the container ready for the components to be added.
     Container pane = getContentPane();
     setContentPane(pane);

     //Setting up the container layout
     GridLayout grid = new GridLayout(1,2);
     pane.setLayout(grid);
     
     //Creating a connection to MS Access and fetch errors using "try-catch" to check if it is successfully connected or not.
     try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    db = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=addItemDB.mdb;";
    con = DriverManager.getConnection(db,"","");
    st = con.createStatement();
    
   } catch (Exception e) {
    JOptionPane.showMessageDialog(null,"Failed to Connect to Database","Error Connection", JOptionPane.WARNING_MESSAGE);
    System.exit(0);
   }
   
  //Implemeting Even-Listener on JButton buttons[0] which is ID
  buttons[0].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
    try {
     listBox.removeAllItems();
     //SQL for selecting the table "person" in the Database
     rs=st.executeQuery("select * from person");
     while (rs.next()) {
      //Displaying the field "id" from the table "person" in JComboBox
         listBox.addItem(rs.getString("id"));
     }
     
    } catch (Exception e) {
     System.out.println("Retrieving Data Fail");
    }
   }
  }
  );
  
  //Implemeting Even-Listener on JButton buttons[1] which is First Name
  buttons[1].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
    try {
     listBox.removeAllItems();
     //SQL for selecting the table "person" in the Database
     rs=st.executeQuery("select * from person");
     while (rs.next()) {
      //Displaying the field "firstName" from the table "person" in JComboBox
         listBox.addItem(rs.getString("firstName"));
     }
     
    } catch (Exception e) {
     System.out.println("Retrieving Data Fail");
    }
   }
  }
  );
  
  //Implemeting Even-Listener on JButton buttons[2] which is Middle Name
  buttons[2].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
    try {
     listBox.removeAllItems();
     //SQL for selecting the table "person" in the Database
     rs=st.executeQuery("select * from person");
     while (rs.next()) {
      //Displaying the field "middleName" from the table "person" in JComboBox
         listBox.addItem(rs.getString("middleName"));
     }
     
    } catch (Exception e) {
     System.out.println("Retrieving Data Fail");
    }
   }
  }
  );
  
  //Implemeting Even-Listener on JButton buttons[3] which is Last Name
  buttons[3].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
    try {
     listBox.removeAllItems();
     //SQL for selecting the table "person" in the Database
     rs=st.executeQuery("select * from person");
     while (rs.next()) {
      //Displaying the field "lastName" from the table "person" in JComboBox
         listBox.addItem(rs.getString("familyName"));
     }
     
    } catch (Exception e) {
     System.out.println("Retrieving Data Fail");
    }
   }
  }
  );
  
  //Implemeting Even-Listener on JButton buttons[4] which is Age
  buttons[4].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
    try {
     listBox.removeAllItems();
     //SQL for selecting the table "person" in the Database
     rs=st.executeQuery("select * from person");
     while (rs.next()) {
      //Displaying the field "age" from the table "person" in JComboBox
         listBox.addItem(rs.getString("age"));
     }
     
    } catch (Exception e) {
     System.out.println("Retrieving Data Fail");
    }
   }
  }
  );
        
     //Adding components to the container
  pane.add(p1);
  pane.add(p2);
  
     /**Set all the Components Visible.
      * If it is set to "false", the components in the container will not be visible.
      */
     setVisible(true);
     setResizable(false);
    }
    
 //Main Method
    public static void main (String[] args) {
     retrieveDBUsingJCB rdjcb = new retrieveDBUsingJCB();
 }
}

Important Part of the Program:

//Implemeting Even-Listener on JButton buttons[0] which is ID
  buttons[0].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
    try {
     listBox.removeAllItems();
     //SQL for selecting the table "person" in the Database
     rs=st.executeQuery("select * from person");
     while (rs.next()) {
      //Displaying the field "id" from the table "person" in JComboBox
         listBox.addItem(rs.getString("id"));
     }
     
    } catch (Exception e) {
     System.out.println("Retrieving Data Fail");
    }
   }
  }
  );
  
  //Implemeting Even-Listener on JButton buttons[1] which is First Name
  buttons[1].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
    try {
     listBox.removeAllItems();
     //SQL for selecting the table "person" in the Database
     rs=st.executeQuery("select * from person");
     while (rs.next()) {
      //Displaying the field "firstName" from the table "person" in JComboBox
         listBox.addItem(rs.getString("firstName"));
     }
     
    } catch (Exception e) {
     System.out.println("Retrieving Data Fail");
    }
   }
  }
  );
  
  //Implemeting Even-Listener on JButton buttons[2] which is Middle Name
  buttons[2].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
    try {
     listBox.removeAllItems();
     //SQL for selecting the table "person" in the Database
     rs=st.executeQuery("select * from person");
     while (rs.next()) {
      //Displaying the field "middleName" from the table "person" in JComboBox
         listBox.addItem(rs.getString("middleName"));
     }
     
    } catch (Exception e) {
     System.out.println("Retrieving Data Fail");
    }
   }
  }
  );
  
  //Implemeting Even-Listener on JButton buttons[3] which is Last Name
  buttons[3].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
    try {
     listBox.removeAllItems();
     //SQL for selecting the table "person" in the Database
     rs=st.executeQuery("select * from person");
     while (rs.next()) {
      //Displaying the field "lastName" from the table "person" in JComboBox
         listBox.addItem(rs.getString("familyName"));
     }
     
    } catch (Exception e) {
     System.out.println("Retrieving Data Fail");
    }
   }
  }
  );
  
  //Implemeting Even-Listener on JButton buttons[4] which is Age
  buttons[4].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
    try {
     listBox.removeAllItems();
     //SQL for selecting the table "person" in the Database
     rs=st.executeQuery("select * from person");
     while (rs.next()) {
      //Displaying the field "age" from the table "person" in JComboBox
         listBox.addItem(rs.getString("age"));
     }
     
    } catch (Exception e) {
     System.out.println("Retrieving Data Fail");
    }
   }
  }
  );

Retrieve Data from Database and Display Using JList

Program Description:

The Program below is a Java Code that demonstrates on how to retrieve data from MS Access database and display it using JList. It has five buttons that corresponds to the database fields you want to display in the JList. This technique is commonly used in many programs so I have created a simple and easy to understand java codes in order to understand the flow of the whole program easily. Always refer to "Important Part of the Program".

Download: retrieveDBUsingJList.rar

Output:
Code:

/**
 * File: retrieveDBUsingJList.java
 * Tiltle: Retrieve Database and Display Using JList
 * Author: http://java-program-sample.blogspot.com/
 */

//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

public class retrieveDBUsingJList extends JFrame {
 
 //Initializing program components
 private DefaultListModel model;
 private JButton buttons[];
 private JList dbList;
 private JPanel p1,p2;
 private String bLabel[] = {"ID","First Name","Middle Name","Last Name","Age"};
 
 Connection con;
 Statement st;
 ResultSet rs;
 String db;

 //Setting up GUI
    public retrieveDBUsingJList() {
     
     //Setting up the Title of the Window
     super("Retrieve DB and Display Using JList");

     //Set Size of the Window (WIDTH, HEIGHT)
     setSize(300,200);

     //Exit Property of the Window
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          
     //Constructing JButtons, JList, and DefaultListModel
     model = new DefaultListModel();
     buttons = new JButton[5];
     dbList = new JList(model);
     
     //Setting up JList property
     dbList.setVisibleRowCount(5);
     dbList.setFixedCellHeight(27);
     dbList.setFixedCellWidth(130);
     dbList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
  
  //Constructing JPanel 1 and its property
  p1 = new JPanel();
  p1.setBorder(BorderFactory.createTitledBorder("Database: "));
  p1.add(new JScrollPane(dbList)); //Adding JList in JPanel 1
  
  //Constructing JPanel 2 and its property
  p2 = new JPanel();
  p2.setLayout(new GridLayout(5,1));
  p2.setBorder(BorderFactory.createTitledBorder("Display: "));
  
  //Constructing all 5 JButtons using "for loop" and add it in JPanel 2
  for(int count=0; count<buttons.length; count++) {
   buttons[count] = new JButton(bLabel[count]);
   p2.add(buttons[count]);
  }
  
  //Setting up the container ready for the components to be added.
     Container pane = getContentPane();
     setContentPane(pane);

     //Setting up the container layout
     GridLayout grid = new GridLayout(1,2);
     pane.setLayout(grid);
     
     //Creating a connection to MS Access and fetch errors using "try-catch" to check if it is successfully connected or not.
     try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    db = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=addItemDB.mdb;";
    con = DriverManager.getConnection(db,"","");
    st = con.createStatement();  
    
   } catch (Exception e) {
    JOptionPane.showMessageDialog(null,"Failed to Connect to Database","Error Connection", JOptionPane.WARNING_MESSAGE);
    System.exit(0);
   }
   
  //Implemeting Even-Listener on JButton buttons[0] which is ID
  buttons[0].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
    try {
     model.clear();
     rs=st.executeQuery("select * from person");
     while (rs.next()) {
         model.addElement(rs.getString("id"));
     }
     
    } catch (Exception e) {
     System.out.println("Retrieving Data Fail");
    }
   }
  }
  );
  
  //Implemeting Even-Listener on JButton buttons[1] which is First Name
  buttons[1].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
     try {
     model.clear();
     rs=st.executeQuery("select * from person");
     while (rs.next()) {
         model.addElement(rs.getString("firstName"));
     }
     
    } catch (Exception e) {
     System.out.println("Retrieving Data Fail");
    }
   }
  }
  );
  
  //Implemeting Even-Listener on JButton buttons[2] which is Middle Name
  buttons[2].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
     try {
     model.clear();
     rs=st.executeQuery("select * from person");
     while (rs.next()) {
         model.addElement(rs.getString("middleName"));
     }
     
    } catch (Exception e) {
     System.out.println("Retrieving Data Fail");
    }
   }
  }
  );
  
  //Implemeting Even-Listener on JButton buttons[3] which is Last Name
  buttons[3].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
     try {
     model.clear();
     rs=st.executeQuery("select * from person");
     while (rs.next()) {
         model.addElement(rs.getString("familyName"));
     }
     
    } catch (Exception e) {
     System.out.println("Retrieving Data Fail");
    }
   }
  }
  );
  
  //Implemeting Even-Listener on JButton buttons[4] which is Age
  buttons[4].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
     try {
     model.clear();
     rs=st.executeQuery("select * from person");
     while (rs.next()) {
         model.addElement(rs.getString("age"));
     }
     
    } catch (Exception e) {
     System.out.println("Retrieving Data Fail");
    }
   }
  }
  );
        
     //Adding components to the container
  pane.add(p1);
  pane.add(p2);
  
     /**Set all the Components Visible.
      * If it is set to "false", the components in the container will not be visible.
      */
     setVisible(true);
     setResizable(false);
    }
    
 //Main Method
    public static void main (String[] args) {
     retrieveDBUsingJList rdjl = new retrieveDBUsingJList();
 }
}

Important Part of the Program:

//Implemeting Even-Listener on JButton buttons[0] which is ID
  buttons[0].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
    try {
     model.clear();
     rs=st.executeQuery("select * from person");
     while (rs.next()) {
         model.addElement(rs.getString("id"));
     }
     
    } catch (Exception e) {
     System.out.println("Retrieving Data Fail");
    }
   }
  }
  );
  
  //Implemeting Even-Listener on JButton buttons[1] which is First Name
  buttons[1].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
     try {
     model.clear();
     rs=st.executeQuery("select * from person");
     while (rs.next()) {
         model.addElement(rs.getString("firstName"));
     }
     
    } catch (Exception e) {
     System.out.println("Retrieving Data Fail");
    }
   }
  }
  );
  
  //Implemeting Even-Listener on JButton buttons[2] which is Middle Name
  buttons[2].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
     try {
     model.clear();
     rs=st.executeQuery("select * from person");
     while (rs.next()) {
         model.addElement(rs.getString("middleName"));
     }
     
    } catch (Exception e) {
     System.out.println("Retrieving Data Fail");
    }
   }
  }
  );
  
  //Implemeting Even-Listener on JButton buttons[3] which is Last Name
  buttons[3].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
     try {
     model.clear();
     rs=st.executeQuery("select * from person");
     while (rs.next()) {
         model.addElement(rs.getString("familyName"));
     }
     
    } catch (Exception e) {
     System.out.println("Retrieving Data Fail");
    }
   }
  }
  );
  
  //Implemeting Even-Listener on JButton buttons[4] which is Age
  buttons[4].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
     try {
     model.clear();
     rs=st.executeQuery("select * from person");
     while (rs.next()) {
         model.addElement(rs.getString("age"));
     }
     
    } catch (Exception e) {
     System.out.println("Retrieving Data Fail");
    }
   }
  }
  );

Sunday, October 9, 2011

Scan Database using First, Last, Next, and Previous Function

Program Description:

The Java Program below is a simple code on how to use the function First, Last, Next, and Previous in scanning data from MS Access Database. I made this program as simple and as short as possible in order to understand easily. It has been tested several times to make sure it runs perfectly. You can download the whole program below including the database to test properly:

Download: scanDatabase.rar

Output:
Code:

/**
 * File: scanDatabase.java
 * Tiltle: Scan Database Using First, Last, Next, Previous
 * Author: http://java-program-sample.blogspot.com/
 */

//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

public class scanDatabase extends JFrame {
 
 //Initializing Program Components
 private JTextField inputs[];
 private JButton scan[];
 private String butLabel[] = {"First","Last","Next","Prev"};
 private JLabel labels[];
 private String fldLabel[] = {"ID","First Name: ","Middle Name: ","Family Name: ","Age: "};
 private JPanel p1,p2;
 
 Connection con;
 Statement st;
 ResultSet rs;
 String db;

 //Setting up GUI
    public scanDatabase() {
     
     //Setting up the Title of the Window
     super("Scan Database");

     //Set Size of the Window (WIDTH, HEIGHT)
     setSize(305,160);

     //Exit Property of the Window
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  
  //Constructing Program Components
     inputs = new JTextField[5];
     labels = new JLabel[5];
     scan = new JButton[4];
     p1 = new JPanel();
     p1.setLayout(new GridLayout(5,2));
     p2 = new JPanel();
     p2.setLayout(new GridLayout(1,1));

     //Setting up the container ready for the components to be added.
     Container pane = getContentPane();
     setContentPane(pane);
     
     //Creating a connection to MS Access and fetching errors using "try-catch" to check if it is successfully connected or not.
     try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    db = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=addItemDB.mdb;";
    con = DriverManager.getConnection(db,"","");
    st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
    
    rs=st.executeQuery("select * from person");
    rs.first();
    
    JOptionPane.showMessageDialog(null,"Successfully Connected to Database","Confirmation", JOptionPane.INFORMATION_MESSAGE);
    
   } catch (Exception e) {
    JOptionPane.showMessageDialog(null,"Failed to Connect to Database","Error Connection", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
   }
     
     //Constructing JLabel and JTextField using "for loop" in their desired order
     for(int count=0; count<inputs.length && count<labels.length; count++) {
      labels[count] = new JLabel(fldLabel[count]);
      inputs[count] = new JTextField(30);
      //Adding the JLabel and the JTextFied in JPanel 1
      p1.add(labels[count]);
      p1.add(inputs[count]);
     }
     
     //Constructing JButton using "for loop"
     for(int count=0; count<scan.length; count++) {
      scan[count] = new JButton(butLabel[count]);
      //Adding the JButton in JPanel 2
      p2.add(scan[count]);
     }
     
  //Implemeting Even-Listener on JButton first
  scan[0].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
    try {
     
     rs=st.executeQuery("select * from person");
     if (rs.first())
      displayRes();
      
    }catch (Exception e ) {
     System.out.println("Fail to Connect to the Database");
    }
   }
  }
  );
  
  //Implemeting Even-Listener on JButton last
  scan[1].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
    try {
     
     rs=st.executeQuery("select * from person");
     if (rs.last())
      displayRes();
      
    }catch (Exception e ) {
     System.out.println("Fail to Connect to the Database");
    }
   }
  }
  );
  
  //Implemeting Even-Listener on JButton next
  scan[2].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
    try {
     
     if(rs!=null || (!rs.next()))
      rs.next();
      displayRes();
      
    }catch (Exception e ) {
     System.out.println("You have reached the last Data.");
    }
   }
  }
  );
  
  //Implemeting Even-Listener on JButton last
  scan[3].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
    try {
     
     if(rs!=null)
      rs.previous();
      displayRes();
      
    }catch (Exception e ) {
     System.out.println("You have reached the first Data.");
    }
   }
  }
  );
  
  //Adding JPanel 1 and 2 to the container
  pane.add(p1, BorderLayout.NORTH);
  pane.add(p2, BorderLayout.SOUTH);
  
     /**Set all the Components Visible.
      * If it is set to "false", the components in the container will not be visible.
      */
     setVisible(true);
     setResizable(false);
    }
    
    //Creating a method used to retrieve data from database and display in JTextField
    public void displayRes() throws Exception {
     inputs[0].setText(rs.getString(1));
     inputs[1].setText(rs.getString(2));
     inputs[2].setText(rs.getString(3));
     inputs[3].setText(rs.getString(4));
     inputs[4].setText(rs.getString(5));
    }
    
 //Main Method
    public static void main (String[] args) {
     scanDatabase sd = new scanDatabase();
 }
}

Important Part of the Program:

//Implemeting Even-Listener on JButton first
  scan[0].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
    try {
     
     rs=st.executeQuery("select * from person");
     if (rs.first())
      displayRes();
      
    }catch (Exception e ) {
     System.out.println("Fail to Connect to the Database");
    }
   }
  }
  );
  
  //Implemeting Even-Listener on JButton last
  scan[1].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
    try {
     
     rs=st.executeQuery("select * from person");
     if (rs.last())
      displayRes();
      
    }catch (Exception e ) {
     System.out.println("Fail to Connect to the Database");
    }
   }
  }
  );
  
  //Implemeting Even-Listener on JButton next
  scan[2].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
    try {
     
     if(rs!=null || (!rs.next()))
      rs.next();
      displayRes();
      
    }catch (Exception e ) {
     System.out.println("You have reached the last Data.");
    }
   }
  }
  );
  
  //Implemeting Even-Listener on JButton last
  scan[3].addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
    try {
     
     if(rs!=null)
      rs.previous();
      displayRes();
      
    }catch (Exception e ) {
     System.out.println("You have reached the first Data.");
    }
   }
  }
  );

Saturday, October 8, 2011

Adding Data to the Database using MS Access

Program Description:

The Program below is a very short, easy-to-understand java code that allows the user to add data to the database. The program is capable of detecting connection errors and input errors. You can download the whole program below including the database to properly test:

Download: addItemToDatabase.rar

Output:
Code:

/**
 * File: addItemToDatabase.java
 * Tiltle: Adding Data to the Database
 * Author: http://java-program-sample.blogspot.com/
 */

//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

public class addItemToDatabase extends JFrame {
 
 //Initializing Components
 private JTextField inputs[];
 private JButton add, reset;
 private JLabel labels[];
 private String fldLabel[] = {"First Name: ","Middle Name: ","Family Name: ","Age: "};
 private JPanel p1;
 
 Connection con;
 Statement st;
 ResultSet rs;
 String db;

 //Setting up GUI
    public addItemToDatabase() {
     
     //Setting up the Title of the Window
     super("Adding Data to the Database");

     //Set Size of the Window (WIDTH, HEIGHT)
     setSize(300,180);

     //Exit Property of the Window
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  
  //Constructing Components
     inputs = new JTextField[4];
     labels = new JLabel[4];
     add = new JButton("Add");
     reset = new JButton("Reset");
     p1 = new JPanel();
     
     //Setting Layout on JPanel 1 with 5 rows and 2 column
     p1.setLayout(new GridLayout(5,2));

     //Setting up the container ready for the components to be added.
     Container pane = getContentPane();
     setContentPane(pane);

     //Setting up the container layout
     GridLayout grid = new GridLayout(1,1,0,0);
     pane.setLayout(grid);
     
     //Creating a connection to MS Access and fetching errors using "try-catch" to check if it is successfully connected or not.
     try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    db = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=addItemDB.mdb;";
    con = DriverManager.getConnection(db,"","");
    st = con.createStatement();  
    
    JOptionPane.showMessageDialog(null,"Successfully Connected to Database","Confirmation", JOptionPane.INFORMATION_MESSAGE);
    
   } catch (Exception e) {
    JOptionPane.showMessageDialog(null,"Failed to Connect to Database","Error Connection", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
   }
     
     //Constructing JLabel and JTextField using "for loop" in their desired order
     for(int count=0; count<inputs.length && count<labels.length; count++) {
      labels[count] = new JLabel(fldLabel[count]);
      inputs[count] = new JTextField(20);
      
      //Adding the JLabel and the JTextFied in JPanel 1
      p1.add(labels[count]);
      p1.add(inputs[count]);
     }
     
     //Implemeting Even-Listener on JButton add
  add.addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
    
    if (inputs[0].getText().equals("") || inputs[1].getText().equals("") || inputs[2].getText().equals("") || inputs[0].getText() == null || inputs[1].getText() == null || inputs[2].getText() == null)
     JOptionPane.showMessageDialog(null,"Fill up all the Fields","Error Input", JOptionPane.ERROR_MESSAGE);
     
    else
     
    try {
     
     String add = "insert into person (firstName,middleName,familyName,age) values ('"+inputs[0].getText()+"','"+inputs[1].getText()+"','"+inputs[2].getText()+"',"+inputs[3].getText()+")";
     st.execute(add); //Execute the add sql
     
     Integer.parseInt(inputs[3].getText()); //Convert JTextField Age in to INTEGER
     
     JOptionPane.showMessageDialog(null,"Item Successfully Added","Confirmation", JOptionPane.INFORMATION_MESSAGE);
     
    }catch (NumberFormatException e) {
     JOptionPane.showMessageDialog(null,"Please enter an integer on the Field AGE","Error Input", JOptionPane.ERROR_MESSAGE);
    }catch (Exception ei) {
     JOptionPane.showMessageDialog(null,"Failure to Add Item. Please Enter a number on the Field AGE","Error Input", JOptionPane.ERROR_MESSAGE);
    }
   }
  }
  );
  
  //Implemeting Even-Listener on JButton reset
  reset.addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
    inputs[0].setText(null);
    inputs[1].setText(null);
    inputs[2].setText(null);
    inputs[3].setText(null);
   }
  }
  );
  
  //Adding JButton "add" and "reset" to JPanel 1 after the JLabel and JTextField
  p1.add(add);
  p1.add(reset);
  
  //Adding JPanel 1 to the container
  pane.add(p1);
  
     /**Set all the Components Visible.
      * If it is set to "false", the components in the container will not be visible.
      */
     setVisible(true);
    }
    
 //Main Method
    public static void main (String[] args) {
     addItemToDatabase aid = new addItemToDatabase();
 }
}

Important Part of the Program:

//Implemeting Even-Listener on JButton add
  add.addActionListener(
  new ActionListener() {
   
   //Handle JButton event if it is clicked
   public void actionPerformed(ActionEvent event) {
    
    if (inputs[0].getText().equals("") || inputs[1].getText().equals("") || inputs[2].getText().equals("") || inputs[0].getText() == null || inputs[1].getText() == null || inputs[2].getText() == null)
     JOptionPane.showMessageDialog(null,"Fill up all the Fields","Error Input", JOptionPane.ERROR_MESSAGE);
     
    else
     
    try {
     
     String add = "insert into person (firstName,middleName,familyName,age) values ('"+inputs[0].getText()+"','"+inputs[1].getText()+"','"+inputs[2].getText()+"',"+inputs[3].getText()+")";
     st.execute(add); //Execute the add sql
     
     Integer.parseInt(inputs[3].getText()); //Convert JTextField Age in to INTEGER
     
     JOptionPane.showMessageDialog(null,"Item Successfully Added","Confirmation", JOptionPane.INFORMATION_MESSAGE);
     
    }catch (NumberFormatException e) {
     JOptionPane.showMessageDialog(null,"Please enter an integer on the Field AGE","Error Input", JOptionPane.ERROR_MESSAGE);
    }catch (Exception ei) {
     JOptionPane.showMessageDialog(null,"Failure to Add Item. Please Enter a number on the Field AGE","Error Input", JOptionPane.ERROR_MESSAGE);
    }
   }
  }
  );

Feel free to comment if the program doesn't work or if you have questions about the program. It has been tested many time so it runs perfectly.

Monday, September 26, 2011

Connect to MS Access Database

Program Description:

There are lots of versions of java codes out there demonstrating on how to connect java application to MS Access Database. Now I have created my own, simple, short, and easy to understand java code on how to connect to MS Access. What it does is that if you run the program, it will terminate if the connection to the database fails and if it succeeded a window will appear. To test the program if it is properly connected, just click the "Test Connection" button. The program will again terminate if the test connection fails and if it succeeded, a confirmation message will be stored in the database.

In order the program to work, you have to create a MS Access file with a filename "database", create a table name "Confirm" and in that table, create two fields name "confirm" and "confirm_to". You have to create the MS Access file in the folder where your java program is because of the code

db = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=database.mdb;";

which means your program can easily access or connect to the database as long as they are in the same folder.

Output:
Code:

/**
 * File: databaseCon.java
 * Tiltle: Database Connection Using MS Access
 * Author: http://java-program-sample.blogspot.com/
 */

//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

public class databaseCon extends JFrame implements ActionListener {
 
 //Initializing components
 private JButton connect;
 private JTextField confirmation;
 Connection con;
 Statement st;
 ResultSet rs;
 String db;

 //Setting up GUI
    public databaseCon() {
     
     //Setting up the Title of the Window
     super("MS Access Connection");

     //Set Size of the Window (WIDTH, HEIGHT)
     setSize(250,95);

     //Exit Property of the Window
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  
  //Constructing Components
     connect = new JButton("Test Connection");
     confirmation = new JTextField(20);

     //Setting up the container ready for the components to be added.
     Container pane = getContentPane();
     setContentPane(pane);

     //Setting up the container layout
     FlowLayout flow = new FlowLayout(FlowLayout.CENTER);
     pane.setLayout(flow);
     
     //Creating a connection to MS Access and fetching errors using "try-catch" to check if it is successfully connected or not.
     try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    db = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=database.mdb;";
    con = DriverManager.getConnection(db,"","");
    st = con.createStatement();  
    
    confirmation.setText("Successfully Connected to Database");
    
   } catch (Exception e) {
    JOptionPane.showMessageDialog(null,"Failed to Connect to Database","Error Connection", JOptionPane.WARNING_MESSAGE);
    System.exit(0);
   }
   
   //Adding Event Listener to the button "Connect"
     connect.addActionListener(this);
     
     //Adding components to the container
  pane.add(confirmation);
  pane.add(connect);
  
     /**Set all the Components Visible.
      * If it is set to "false", the components in the container will not be visible.
      */
     setVisible(true);
    }
    
    //Creating an event to the JButton "Connect"
    public void actionPerformed(ActionEvent event) {
     
     try {
      if(event.getSource() == connect ) {
       
       //Adding values on the database field "confirm" and "confirm_to"
       String insert = "insert into Confirm (confirm, confirm_to) values ('"+confirmation.getText()+"','"+confirmation.getText()+"')";
    st.execute(insert); //Execute the sql
    
    //This will display if the connection and the insertion of data to the database is successful.
    confirmation.setText("Test Successful");
    
    //Display what is in the database
    rs=st.executeQuery("select * from Confirm");
    while(rs.next()) {
     System.out.println(rs.getString("confirm"));
    }
      }
     }catch(Exception e) {
      JOptionPane.showMessageDialog(null,"Failed to Connect to Database","Error Connection", JOptionPane.WARNING_MESSAGE);
   System.exit(0);
     }
    }
    
 //Main Method
    public static void main (String[] args) {
     databaseCon pjtf = new databaseCon();
 }
}

Important Part of the Program:

//Creating a connection to MS Access and fetching errors using "try-catch" to check if it is successfully connected or not.
     try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    db = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=database.mdb;";
    con = DriverManager.getConnection(db,"","");
    st = con.createStatement();  
    
    confirmation.setText("Successfully Connected to Database");
    
   } catch (Exception e) {
    JOptionPane.showMessageDialog(null,"Failed to Connect to Database","Error Connection", JOptionPane.WARNING_MESSAGE);
    System.exit(0);
   }

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Hostgator Discount Code