javams-accessucanaccess

Manipulating an Access database from Java without ODBC


I want to manipulate a Microsoft Access database (.accdb or .mdb file) from my Java project. I don't want to use the JDBC-ODBC Bridge and the Access ODBC driver from Microsoft because:

I have seen other answers mentioning a JDBC driver for Access databases named UCanAccess. How can I set up my Java project to use this approach?

(Answers suggesting better ways of working with Access databases from Java would also be most welcome.)


Solution

  • UCanAccess is a pure Java JDBC driver that allows us to read from and write to Access databases without using ODBC. It uses two other packages, Jackcess and HSQLDB, to perform these tasks. The following is a brief overview of how to get it set up.

      Option 1: Using Maven

    If your project uses Maven you can simply include UCanAccess via the following coordinates:

    groupId: io.github.spannm
    artifactId: ucanaccess

    The following is an excerpt from pom.xml, you may need to update the <version> to get the most recent release:

    <dependency>
        <groupId>io.github.spannm</groupId>
        <artifactId>ucanaccess</artifactId>
        <version>5.1.2</version>
    </dependency>
    

      Option 2: Manually adding the JAR to your project

    UCanAccess provides its standard dependencies in its uber.jar file. Usually all you need to do is add that file to your project. (Additional dependencies are required for working with encrypted .accdb files. See the UCanAccess documentation for details.)

    Go to UCanAccess on Maven Central, Browse the latest version, and download the uber.jar file.

    Eclipse: Right-click the project in Package Explorer and choose Build Path > Configure Build Path.... Click the "Add External JARs..." button to add the uber.jar file. When you are finished your Java Build Path should look something like this

    enter image description here

      That's it!

    Now you can access data in .accdb and .mdb files using code like this

    // assumes...
    //     import java.sql.*;
    Connection conn=DriverManager.getConnection(
            "jdbc:ucanaccess://C:/__tmp/test/zzz.accdb");
    Statement s = conn.createStatement();
    ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
    while (rs.next()) {
        System.out.println(rs.getString(1));
    }
    

      Disclosure

    At the time of writing this Q&A I had no involvement in or affiliation with the UCanAccess project; I just used it. I later became a contributor to the project.