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-code-complete.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);
}

No comments:

Post a Comment