Thursday 27 September 2012

Java Database connection using MS-Access

This is a small java program which is used to test connection between Java and MS-Access.
1) Create a MS-Access database "Confirm".
    Field Names:- confirm, confirm_to as Text data type

2) Type the following code in the notepad
3) Run the program.

    //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(); 
     } 
    }