eclipse中的数据库连接 - ClassNotFoundException

时间:2013-11-07 10:42:42

标签: eclipse jdbc

我在Eclipse中创建了MySQL的连接配置文件。我编写了这段代码:

public static void main(String[] args) {

        Connection conn;

        try {
            Class.forName("com.mysql.jdbc.Driver");

            String url="jdbc:mysql://localhost:3306/test1";
            conn= DriverManager.getConnection(url,"root","swathi");

            Statement stmt= conn.createStatement();
            String query="select * from sample";

            System.out.println(stmt.executeQuery(query));

        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

我已经设置了

classpath=C:\Program Files\MySQL\MySQL Connector J\mysql-connector-java-5.1.26-bin.jar

当我运行程序时,我收到此错误:

java.lang.NoClassDefFoundError: C:\Users\swathi\workspace\project1;C:\Program
Caused by: java.lang.ClassNotFoundException: C:\Users\swathi\workspace\project1;C:\Program
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Exception in thread "main" 

3 个答案:

答案 0 :(得分:1)

扩展项目的类路径的正确方法是编辑该项目的设置:

Right click on your project > Build Path > Configure Build Path...

转到标签Libraries然后

点击Add External JARs...,找到jdbc驱动程序,然后点击open,然后点击OK

或者

点击Add Library...然后点击User Library并点击Next >。点击User Libraries,然后点击New...。输入您的lib的名称,例如JDBC_DRIVER_MYSQL_5,然后点击Add External JARs...

我建议您将项目转换为maven项目并将其添加为依赖项:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
</dependency>

答案 1 :(得分:0)

问题是,您的classpath包含空格。试着引用它。

答案 2 :(得分:0)

无需执行

set CLASSPATH=%CLASSPATH%;JAVA_HOME\lib;

只需将mysql-connector-java-5.1.26-bin.jar:添加到/WEB-INF/lib目录。

Eclipse非常聪明,能够识别/WEB-INF/lib下添加的.jar文件,并且应该包含在CLASSPATH中。