java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Exception occurring. Why?

hina abbasi picture hina abbasi · Apr 10, 2014 · Viewed 192.5k times · Source

I have created an MS Access database and assigned a DSN to it. I want to access it through my Java application.

This is what I am doing:

public class AccessDbConnection {

    public static void main(String[] args) {
        System.out.println("**ACCESS DB CONNECTION**");

        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // for MS Access ... MS access driver loading

            String     conURL    = "jdbc:odbc:sampleDNS";
            Connection con       = DriverManager.getConnection(conURL);
            Statement  statement = con.createStatement();
            String     qry       = "SELECT * FROM Table1";
            ResultSet  rs        = statement.executeQuery(qry);

            while(rs.next()) {
                String id    = rs.getString("ID") ;
                String fname = rs.getString("First_Name");
                String lname = rs.getString("Last_Name");
                System.out.println(id + fname + lname);
            }
        } catch (ClassNotFoundException ex) {
            System.out.println("Classforname Exception!!");
            Logger.getLogger(AccessDbConnection.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            System.out.println("DriverManager Exception!!");
            Logger.getLogger(AccessDbConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

I am getting the exception at the first line of try block. That is class.forname("..");. Why am I having this Exception?

Answer

Gord Thompson picture Gord Thompson · Apr 10, 2014

For Java 7 you can simply omit the Class.forName() statement as it is not really required.

For Java 8 you cannot use the JDBC-ODBC Bridge because it has been removed. You will need to use something like UCanAccess instead. For more information, see

Manipulating an Access database from Java without ODBC