radar33 radar33 - 10 months ago 32
Java Question

MySQL driver class not found, even when included in classpath

I have the following code:


package mypackage;

import mypackage.MainClass;

public class Launcher
public static void main(String[] args)
new MainClass(args);


package mypackage;

import java.sql.*;
import com.mysql.jdbc.Driver;

public class MainClass
public MainClass(String[] args)
catch (Exception ex)
System.err.println("Error: unable to load sql driver class!");

System.out.println("We got here... How???");

The code compiles with no complaints using

javac -cp src;bin;lib\mysql-connector-java-5.1.38-bin.jar -sourcepath src -d bin src\mypackage\Launcher.java
jar cfe myjar.jar mypackage.Launcher .

but when running

java -cp .\mysql-connector-java-5.1.38-bin.jar -jar myjar.jar

I get the following error:

Error: unable to load sql driver class!
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at mypackage.MainClass.<init>(MainClass.java:10)
at mypackage.Launcher.main(Launcher.java:9)

I don't understand what I am missing here, and I have spent over 6 hours attempting to debug and searching for answers, but I have not found anything that has helped (pretty much everything I've found says "include the jarfile containing the class on the classpath – but I've very clearly done just that).

What's going on?

Answer Source

-jar option

... When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.

The quickest way for you to launch it is to drop the -jar option, add your jar to the -cp list and use mypackage.MainClass as the last CLI argument.
(just in case you are not aware) But only after you implement the public static void main(String[] args) method inside that class (no, the fact your class has a constructor doesn't matter)