MS Access Database Connectivity in Java



         It is quiet easy to connect MS Access database through java program. Before proceeding with the program, let me explain some basic concepts used in this program.

Class.forName

              This causes the driver class to dynamically load at  runtime and it causes the driver to get initialized and returns the class object associated with it. If the driver used is correct then the static intializer of the class can be invoked to get the connection. Rest stuffs are self explanatory.


MSdbConnectivity.java - Download source code


import java.sql.*;
public class UserLogin {
public static void main(String[] args) {
try {
// Load MS accces driver class
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

// C:\\databaseFileName.accdb" - location of your database 
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\bank.accdb";

// specify url, username, pasword - make sure these are valid 
Connection conn = DriverManager.getConnection(url, "username", "password");

System.out.println("Connection Succesfull");
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());

}}}

        There are several ways for MS Access Database Connection, among them I have explained one.






Reactions:

8 comments :

  1. thank you very much, c'est très gentille

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Connection conn = DriverManager.getConnection(url, "username", "password");
    In this what is url,username,password??

    ReplyDelete
    Replies
    1. Hi Shobika,
      String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\bank.accdb";

      URL is the path to your database file. Replace "C:\\bank.accdb" with your database location including file name.

      If you haven't set any username, password already those fields can be left empty; for example;
      Connection con = DriverManager.getConnection(url, "", "");

      Delete
  4. Thank you so much for your explanation.
    I'm a beginner in Java to learn in connecting MS Access.
    I would like to ask, how to write relative path for my database?
    for example, my bank.accdb is in the project folder, and I would like to use relative path, so that when I move the project, I can move the whole project folder all at once.

    Thank you again. :)

    Regards,
    Jaleen

    ReplyDelete
  5. Got an exception! java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver
    sun.jdbc.odbc.JdbcOdbcDriver

    ReplyDelete
    Replies
    1. Make sure to have JDBC driver library (jar) in your project build path..

      Delete
  6. how to set connection in dao class for ms access db

    ReplyDelete