简体   繁体   English

MySQL连接器到JDBC的类路径 - 无法加载驱动程序

[英]Classpath for MySQL connector to JDBC-can't load the driver

I was trying to connect to MySQL using JDBC API. 我试图使用JDBC API连接到MySQL。 I have downloaded the MySQL driver which is the "mysql-connector-java-5.1.28-bin jar" file. 我已经下载了MySQL驱动程序,它是“mysql-connector-java-5.1.28-bin jar”文件。 My OS is Windows 7 and I have set the Classpath of Java to following path: 我的操作系统是Windows 7,我已将Java的Classpath设置为以下路径:

"E:\Myclass"

I have copied the above jar file to this folder. 我已将上面的jar文件复制到此文件夹中。 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. 由于我使用的是Eclipse,因此我将JAR文件添加到Eclipse的类路径中。

You have to include the JAR in your classpath: 您必须在类路径中包含JAR:

java -jar yourdriver.jar LoadDriver

JARs are filesystems. JAR是文件系统。 They should be added to your classpath the same way you add directories. 它们应该像添加目录一样添加到类路径中。 Only classes will be loaded from the classpath you specified. 只会从您指定的类路径加载类。

Use the below cmd to run it 使用以下cmd运行它

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 如前所述,mysql jar存在E:\\Myclass\\mysql-connector-java-5.1.28-bin.jar ,只需在类路径中设置并运行它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM