0

So I was just trying out a simple JDBC beginners code that retrieves table rows. It worked well when I ran it on IntelliJ IDEA. but it won't run when I try to run it using the command line.

I have gone through many similar questions but none of them answered my problem. I have tried the following things:

  1. looked for any typo while compiling and running java file ( it was correct )
  2. included the ojdbc8 driver in classpath but that didn't work as well.
  3. I have verified that I have my JDK set in an environmental variable.

and my files are saved as "oracle.java" and my class name is "oracle" if that helps.

import java.sql.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.Class;
class oracle
{
    public static void main(String args[])
    {
        try
        {
            Class.forName("oracle.jdbc.driver.OracleDriver");

            Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

            Statement stmt = con.createStatement();

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

            con.close();
        }

        catch(Exception e)
        {
            System.out.println(e);
        }
    }
}

Output:

C:\Users\mypc\Desktop>java -cp ojdbc8.jar -Xdiag oracle
Error: Could not find or load main class oracle
Caused by: java.lang.ClassNotFoundException: oracle
java.lang.ClassNotFoundException: oracle
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(Unknown Source)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(Unknown Source)
    at java.base/java.lang.ClassLoader.loadClass(Unknown Source)
    at java.base/java.lang.Class.forName0(Native Method)
    at java.base/java.lang.Class.forName(Unknown Source)
    at java.base/sun.launcher.LauncherHelper.loadMainClass(Unknown Source)
    at java.base/sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49
suketu Patel
  • 15
  • 1
  • 8

1 Answers1

0

Assuming you have compiled the file using javac, you then will need to include the location to which you compiled it in the classpath. If you have the simplest possible setup, and invoked javac without the -d argument indicating a compilation destination, it will be located in the same directory as your source file.

If not, assuming your JAR file and your source file are in the same directory, you need to do:

javac -classpath ojdbc8.jar oracle.java`

After that, you need to include the location of the compiled classes in the classpath at runtime. For my example, in which your working directory is the same as the location of the source file and the jar file.

java -classpath ojdbc8.jar;. oracle
David P. Caldwell
  • 3,394
  • 1
  • 19
  • 32