0
votes

I wanted to try using SQL with Java, so I downloaded mysql-connector-java-5.1.18-bin.jar.

I'm using Eclipse, so I went into Eclipse, Project -> Properties and added the jar files.

I also added the following to my classpath:

  1. C:\Users\shahin\Desktop\mysql-connector-java-5.1.18\com\mysql\jdbc\;
  2. C:\Users\shahin\Desktop\mysql-connector-java-5.1.18\mysql-connector-java-5.1.18-bin.jar;

It runs fine in Eclipse, but when I run my. Jar file I get this error:

Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        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 Main.main(Main.java:15)
2
What do you mean, "when I run my jar file"? How are you launching it? - Mike Baranczak

2 Answers

0
votes

Your classpath for the mysql .jar is most likely off. Is your jar located nearby the mysql jar? (If its not being pointed to it) To test this, you can place the two in the same directory and see if it runs.

0
votes

That's because mysql-connector-java-5.1.18-bin.jar isn't in your classpath when you run your jar.

Inside your .jar file there should be a META-INF/MANIFEST.MF file. You need an entry in that file for your classpath that points to where the mysql-connector-java-5.1.18-bin.jar file is located:

Class-Path: path/to/mysql-connector-java-5.1.18-bin.jar

Note this can be local to your jar. A common way to do it is to have a lib subdirectory where your jar is located that contains the other jars yours depends on:

Class-Path: lib/mysql-connector-java-5.1.18-bin.jar