Connect to an Access database in Java using NetBeans

Kaoru picture Kaoru · Nov 15, 2013 · Viewed 44.6k times · Source

How do I connect to an Access database in Java?

I have done like this:

package inspection.management.system;

import java.sql.*;

/**
 *
 * @author Fuhans
 */

public class Database 
{
    public static void DatabaseConnectivity()
    {
        try
        {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

            String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "d:\\program files\\project\\program\\inspection management system\\db1.accdb";

            Connection conn = DriverManager.getConnection(url);

            System.out.println("Connection Successful");
            InfoBox.ShowMessageBox("Connection Successful!", "Success");
        } 

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

            InfoBox.ShowMessageBox("Got an Exception!", "Error");
            InfoBox.ShowMessageBox(e.getMessage(), "Error");
        }
    }
}

if (_textField1.equals("Fuhans") && _passwordField1.equals("Xavega"))
        {
            Sound.PlaySound(1);
            InfoBox.ShowMessageBox("Successfully Login!", "Success");
            Database.DatabaseConnectivity();
        }

When i successfully login, it gave me error on database:

enter image description here

What have i done wrong?

Answer

Gord Thompson picture Gord Thompson · Oct 3, 2014

in the ODBC Administrator app, i don't have Ms access Driver, i just have SQL Driver.

Now that the JDBC-ODBC Bridge has been removed from Java (since Java 8) you should consider using the UCanAccess JDBC driver. It is a pure Java implementation so it works on non-Windows platforms, too.

For more information see

Manipulating an Access database from Java without ODBC