"java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver" error when running from terminal

I have a program that I run from Eclipse successfully.

However, when I want to run it from terminal, I encounter the famous error:

"java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver"

on this line:

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


PS:

I have the following in CLASSPATH:

/oracle/jdbc/lib/ojdbc6.jar

Also note that I compile it successfully (javac Test2.java). Then when I run it (java Test2), I get the following error:

Error: Could not find or load main class Test2

So I run:

java -classpath ~/Desktop/JDBC2/src Test2

It runs, but I get the above "ClassNotFoundException" though.


Solution 1:

I found this question tricky: the reason is related to semicolon after jar file address. At first I changed the directory of MySample.java to another directory (you can don't do that) like C:\ then I removed package address from the source code, at the end I run this command in cmd

java -cp path_to_oracle_driver.jar; MySample

P.S. If you want run it from terminal you have to remove package PackageAddress from the source code and compile it again.

Solution 2:

As @yngwietiger mentioned above in the comments, using -classpath parameter when running the .class file, overrides the original CLASSPATH and the predefined ojdbc6.jar file. So we need to mention both when running:

java -classpath ~/Desktop/JDBC2/src:/oracle/jdbc/lib/ojdbc6.jar Test2 

Or, as a better solution, we can add the current path to CLASSPATH (note the colon and dot at the end):

export CLASSPATH=$CLASSPATH:.

And, in order to run, we just need to type:

Java Test2