Search code examples
javaoracleojdbc

Always got "ClassNotFound" error when trying OpenJDK 11 + ojdbc10.jar for Oracle 19c


Want to run a java program in GCP cloud shell to connect Oracle 19c and the java version there is OpenJDK 11. Always got ClassNotFoundException.

Tried the same OpenJDK (from RedHat) in a Windows 10 laptop and got the same error.

Then I tried JDK 11 (from Oracle) in Windows 10, it worked fine.

Because I have to use OpenJDK in GCP eventually, how can I solve this issue?

Very simple Java code -

import java.sql.*;

class JdbcOracleConnectTest {
    public static void main(String args[]) {
        try {
            // step1 load the driver class
            Class.forName("oracle.jdbc.driver.OracleDriver");

            // step2 create the connection object
            Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "oracle");

            // step3 create the statement object
            Statement stmt = con.createStatement();

            // step4 execute query
            ResultSet rs = stmt.executeQuery("select * from emp");
            while (rs.next())
                System.out.println(rs.getInt(1) + "  " + rs.getString(2) + "  " + rs.getString(3));

            // step5 close the connection object
            con.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
C:\app\jdk11\bin\java -version
openjdk version "11.0.2" 2019-01-15
OpenJDK Runtime Environment 18.9 (build 11.0.2+9)
OpenJDK 64-Bit Server VM 18.9 (build 11.0.2+9, mixed mode)

"ojdbc10.jar" is from Oracle.

C:\app\jdk11\bin\java -cp C:\temp\ojdbc10.jar JdbcOracleConnectionTest
Error: Could not find or load main class JdbcOracleConnectionTest
Caused by: java.lang.ClassNotFoundException: JdbcOracleConnectionTest

Solution

  • Change this line of your code:

    Class.forName("oracle.jdbc.driver.OracleDriver");
    

    to this:

    Class.forName("oracle.jdbc.OracleDriver");
    

    Refer to Oracle documentation, namely JDBC Developer's Guide

    However, you no longer need to explicitly load the [JDBC] driver class so you can actually remove that line altogether. Refer to this SO question:
    Class.forName(JDBC_DRIVER) no longer needed?

    Also, the format of the connection URL has changed. Refer to Oracle Database XE Quick Start. Try the following:

    jdbc:oracle:thin:@//localhost:1521/xe