javajdbcclasspathconnector-j

Classpath contains only the running file


I'm having issues trying to use the Connector/J JDBC driver in my code.

The code I have written uses the Class.forName("com.mysql.jdbc.Driver").newInstance() to load the class before DriverManager.getConnection() is used to load the driver.

This results in the ClassNotFoundException for com.mydql.jdbc.Driver. I have the binary JAR file for the mysql connector, mysql-connector-java-5.1.26-bin.jar.

My code is packaged into a JAR file by building in Netbeans.

To run the code I am using the following

java -classpath "/path/to/mysql-connector-java-5.1.26-bin.jar" -jar MyJarFile.jar

This gives the exception: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

Adding System.out.println(System.getProperty("java.class.path")); to the beginning of the program prints only MyJarFile.jar.

I have tried adding the jar file to the CLASSPATH variable using export, and setting the last part of the -classpath flag to lib/*, but with the same results.

I tried running the program from a .class file, instead. It complained about being unable to find or load the main class. It would run only when both the wildcard was used in the classpath and the MyJarFile.jar was in that location. It would simply hang at the loading of the Driver, though.

Does anyone have any thoughts as to what is going on?


Solution

  • Try don't mix -cp and -jar options, this might work:

    java -cp "mysql-connector-java-5.1.26-bin.jar:MyJarFile.jar" my.package.Main
    

    for *nix or

    java -cp "mysql-connector-java-5.1.26-bin.jar;MyJarFile.jar" my.package.Main
    

    for windows

    where my.package.Main is your main class.