I have a simple example which tries to connect to a database and I could only do it when I unjarred the mysql*.jar file in the working directory.
- I tried to export the /path/to/mysql.jar.file to $PATH and $CLASSPATH and that didn’t work.
- I tried to use include the path like this, but it didn’t work:
javac -cp “.:/usr/share/java/” HelloWorld.java
What could be the issue. Why is it not finding the jar file?
Any thoughts?
You need to set up the classpath when running the JVM as well as running the compiler. The classpath must include the JAR itself, not the folder containing the JAR.
Your line
shows that you are passing a classpath to
javac, the Java compiler, but not the JVM.Let’s use the following simple class, which just connects to MySQL and then disconnects again:
Here’s what happens when I come to run it:
In this case, the MySQL driver JAR isn’t on the classpath, so we get an error when we attempt to load the driver class (
com.mysql.jdbc.Driver).If I add the driver JAR to the classpath using the
-cpcommand-line switch (I have a copy of this JAR in the current directory), it works:(I’m on Windows, so I use
;as a path separator. You appear to be using some dialect of Unix, so you should use:instead.)Similarly, if we add the JAR to the
CLASSPATHenvironment variable, it also works: