抛出java.lang.ClassNotFoundException:com.mysql.jdbc.Driver

18 java exception

我在java.lang.ClassNotFoundException尝试运行代码时遇到异常,

我的守则

   try 
   {
     Class.forName("com.mysql.jdbc.Driver");
     Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/simple",
      "root","root");
     Statement stmt=con.createStatement();
     String query="SELECT * FROM CUST";
     ResultSet rs=stmt.executeQuery(query);
     while(rs.next())
     {
          System.out.print(rs.getString("CUST_NAME") +" ");
          System.out.print(rs.getString(2) +" ");
          System.out.print(rs.getString(3) +" ");

     }    
     rs.close();
     stmt.close();
     con.close();    
  }   
  catch (ClassNotFoundException e) 
  {
     e.printStackTrace();
  }
  catch (SQLException e) 
  {
     e.printStackTrace();
  }    
Run Code Online (Sandbox Code Playgroud)

我收到了错误

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:169)
at Simple.MyProg.main(MyProg.java:15)   
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

aiz*_*zaz 26

问题不在代码中,但您没有将驱动程序添加到您的项目中!您必须将*.jar驱动程序添加到您的项目中......

尝试将它放在lib目录中,然后重新启动tomcat ...

问题是Class.forName("com.mysql.jdbc.Driver"); 它试图加载驱动程序,但它没有得到它,这是你得到的原因:

抛出java.lang.ClassNotFoundException.


小智 15

将*.jar复制到我的WEB-INF/lib文件夹中 - >为我工作.当包含在buildpath上时,每次都有这个errormsg.


小智 5

该问题与 MySql 驱动程序有关

Class.forName("com.mysql.jdbc.Driver");
Run Code Online (Sandbox Code Playgroud)

将 MySQL jdbc 驱动程序 jar 文件添加到类路径中。

我在 JDK 上也有这个错误。我正确构建了 ClassPath,然后将“mysql-connector-java-5.1.25-bin”放入“C:\Program Files\Java\jre7\lib\ext”目录中,我有我的 JDK。然后再次编译并运行,就可以正常工作了。