Database connection in eclipse - ClassNotFoundExce

2019-09-16 02:15发布

问题:

I have created connection profile of MySQL in Eclipse.I have written this code:

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();
        }

    }

i have set the

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

When i run the program i am getting this error:

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" 

回答1:

The proper way to extend your project's class path is to edit the setting for that project:

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

Go to the tab Libraries then

click Add External JARs..., locate the jdbc driver and click open then OK.

Or

click Add Library... then User Library and ckick Next >. Click User Libraries and then click New.... enter a name for your lib, for example JDBC_DRIVER_MYSQL_5 then click Add External JARs....

I would recomend though to convert your project into a maven project and add it as a dependency:

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


回答2:

Problem is, that your classpath contains spaces. Try to quote it.



回答3:

There is no need of doing

set CLASSPATH=%CLASSPATH%;JAVA_HOME\lib;

Just add mysql-connector-java-5.1.26-bin.jar: to /WEB-INF/lib directory.

Eclipse is smart enough to recognize .jar files added under /WEB-INF/lib and should include in the CLASSPATH.



标签: eclipse jdbc