How to get JDBC Connection to MS-Access Database in Java?

DeeKay May 9, 2011 at 2:43 pm · java.sql

Below code shows how to get JDBC Connection to MS Access database –

/****************************************************************************************
 * Created on 05-2011 Copyright(c) http://kodehelp.com All Rights Reserved.
 ****************************************************************************************/
package com.kodehelp.javasql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * Created by http://kodehelp.com
 * Date: 5/9/11
 */
public class GetMSAccessConnection {

    private static final String USERNAME = "USERNAME";
    private static final String PASSWORD = "PASSWORD";
    private static final String DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver";
    private static final String URL = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=C:\\Database\\testdb.mdb;}";
    public static void main(String args[]) throws ClassNotFoundException, SQLException {
        Connection conn = null;
        try{
            Class.forName(DRIVER);
            Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        }catch (ClassNotFoundException cnfEx){
            throw cnfEx;
        }catch (SQLException sqlEx){
            throw sqlEx;
        }finally{
            if(conn!=null){
              conn.close();
            }
        }

    }
}