0
votes

I was trying to connect to MySQL using JDBC API. I have downloaded the MySQL driver which is the "mysql-connector-java-5.1.28-bin jar" file. My OS is Windows 7 and I have set the Classpath of Java to following path:

"E:\Myclass"

I have copied the above jar file to this folder. Then I have written the following code to test if I can load the driver.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class LoadDriver {
public static void main(String[] args) {
    try {
        // The newInstance() call is a work around for some
        // broken Java implementations

        Class.forName("com.mysql.jdbc.Driver").newInstance();
    } catch (Exception ex) {
        // handle the error
        System.out.println("Unable to load Driver Class");
        return;
    }
}
}

I expect everything should be working fine but I always get the "Unable to load Driver Class". Can anyone point out where was wrong? Thanks

Note: Thanks for all your answers. I have solved the problem. Since I am using Eclipse, I have add the JAR file to the classpath of the Eclipse.

2
Don't call newInstance()Brandon
Tried that, still doesn't workOptimus Prime
Explictly declare the class path to point to my JAR'sSathish D
@user3225698 r u running it frm cmd ??Kick
No, I am running with Eclipse.Optimus Prime

2 Answers

2
votes

You have to include the JAR in your classpath:

java -jar yourdriver.jar LoadDriver

JARs are filesystems. They should be added to your classpath the same way you add directories. Only classes will be loaded from the classpath you specified.

0
votes

Use the below cmd to run it

java -cp E:\Myclass\mysql-connector-java-5.1.28-bin.jar; LoadDriver

As mentioned the mysql jar exist @ E:\Myclass\mysql-connector-java-5.1.28-bin.jar , just set in the classpath and run it