Java – Unable to load jdbc driver (ClassNotFoundException)

Unable to load jdbc driver (ClassNotFoundException)… here is a solution to the problem.

Unable to load jdbc driver (ClassNotFoundException)

I’m trying to load the JDBC driver to make some SQL calls to my AS400. I tried running the connection on a machine with JDBC installed and the URL and SQL call worked fine.

I need to develop an app that doesn’t have drivers installed (currently available for Android, but we’re looking to expand to desktop apps). I’m testing the code on an actual Android device, not an emulator, so it has full internet access.

The driver for jt400 is located in com.ibm.as400.access.AS400JDBCDriver at noted by IBM .

Here is my code :

    try {

Class.forName("com.ibm.as400.access.AS400JDBCDriver").newInstance();
        Connection conn = DriverManager.getConnection(
                url + schema + "; naming=sql; errors=full",
                uname,
                psswrd);

 do SQL query stuff

rs.close();
        stmt.close();
        conn.close();

} 
    catch (ClassNotFoundException e)
    {
        this.basicOutput.setText("Class not found: " + e.getMessage());
        System.out.println(e.getStackTrace());
    }
    catch (SQLException e)
    catch (Exception e)  //need generic to catch all errors thrown
    {

this.basicOutput.setText(e.getMessage());
        System.out.println(e.getStackTrace());

}

When I run it, I get “Class not found: com.ibm.as400.access.AS400JDBCDriver”.

I did some research and it shows that Class.forName is not a good approach. So I tried this too:

        DriverManager.registerDriver(new com.ibm.as400.access.AS400JDBCDriver());

But this also produces the same error.

The class is there. The compiled code doesn’t throw any syntax errors, but for some reason, the runtime can’t find it.

What am I missing?

Solution

The driver needs to be included as a jar in your project. If you already have it, add it to your project’s folder/libs.

You specify the driver class as a string literal, so during compilation it passes and you think everything is fine. However, at run time it needs to find it, and because you don’t have a jar that it can’t find.

Related Problems and Solutions