Search code examples
javajarclasspathclassnotfoundexception

java commandline: java.lang.ClassNotFoundException when JAR is in current folder but not when it is decompressed


A simple Java code has this line:

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

The code compiles to generate .class file. But when I try to run this .class file using Java command line, it fail at runtime at above line with exception

Exception in thread "main" java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver

In current folder I already have put required sqljdbc41.jar which has SQLServerDriver driver. I also have included current folder "." in CLASSPATH environment variable (I am on Windows btw).

However, above code line does not give any problem and code runs successfully when I unzip sqljdbc41.jar, which creates folder hierarchy "com\microsoft\sqlserver\jdbc" in the current folder.

Java information:

java version "1.8.0_202"

Java(TM) SE Runtime Environment (build 1.8.0_202-b08)

Java HotSpot(TM) 64-Bit Server VM (build 25.202-b08, mixed mode)

Where I am missing? How and where exactly shall I specify CLASSPATH? How can I include dependent jar files when running code using java command line?


Solution

  • Instead of using the 4-year-old JDBC driver sqljdbc41.jar directly, you should use a dependency management tool, for example, Maven. Then, as described in the driver home page, it can be added to a Maven project by adding it as a dependency in the POM file with the following code:

    <dependency>
        <groupId>com.microsoft.sqlserver</groupId>
        <artifactId>mssql-jdbc</artifactId>
        <version>10.2.1.jre17</version>
    </dependency>
    

    See the Maven Central Repository for the latest version.