1
votes

I'm trying to get the JDBC to work on my Windows 7. I added it to the CLASSPATH ("G:/workspace/mysql-connector-java-5.1.18-bin.jar"). Restarted, because I thought this might be the problem. But the Class.forName("com.mysql.jdbc.Driver").newInstance() still is not working. It throws the following exception:

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 JDBCTest.main(JDBCTest.java:18)  

And this is the code in my class:

....  
private static Connection connect=null;
private static Statement statement=null;
private PreparedStatement preparedstament=null;
private static ResultSet resultset=null;

public static void main(String args[]) throws Exception
{

    Class.forName("com.mysql.jdbc.Driver").newInstance();

    connect=DriverManager.getConnection("jdbc:mysql://localhost/feedback?user=root&password=root");
    statement=connect.createStatement();  

How am I supposed to solve this?

1
I added it to the CLASSPATH - apparently you didn't. What IDE are you using?Tomasz Nurkiewicz
How are you running your code?Jon Skeet
@TomaszNurkiewicz echo %CLASSPATH% says it's in thereAndrew
Note that if you are running your app as an executable JAR (with java -jar myprog.jar), the CLASSPATH environment variable will be ignored. In that case you need to set the classpath in the manifest file of the JAR.Jesper
Since JDBC 4 you don't need anymore to explicitly load the driver with Class.forName("com.mysql.jdbc.Driver"); Btw it's just an info, it actually doesn't resolve your problem.alain.janinm

1 Answers

2
votes

I don't believe Eclipse will use the CLASSPATH environment variable when launching a Java application. You either need to add it to the build path for the project, or explicitly configure the launch configuration to include it. It's probably simpler to add it to the build path:

  • Right click on the project
  • Choose Build Path
  • Choose "Add External Archives"
  • Browse to the jar file