How do I create a connection to MS Access database?

Category: java.sql, viewed: 12361 time(s).

Here is an example about how to create a database connection to MS Access database. To allow the database access to be authenticated the security user account can be add from Tools->Security->User and Group Accounts.

On the example below we can either connect through the DSN created previously on the Windows system or we can create it in our program as the long URL below.

package org.kodejava.example.sql;

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

public class MSAccessConnect {
    //
    // If you want to use you ODBC DSN
    //
    //private static final String URL = "jdbc:odbc:TestDB";

    private static final String USERNAME = "admin";
    private static final String PASSWORD = "welcome";
    private static final String DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver";

    private static final String URL =
        "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=D:\\Database\\testdb.mdb;}";

    public static void main(String[] args) throws Exception {
        Connection connection = null;
        try {
            Class.forName(DRIVER);
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);

            //
            // Do something with the connection here!
            //
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            connection.close();
        }
    }
}

If you want to discuss more about this example you can jump the the forums

Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Can't find what you are looking for? Join our FORUMS and ask some questions!
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats