如何解决java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

Aka*_*ari 6 java mysql jdbc

我编写了这个 java 应用程序来响应来自命令行的数据并将其存储到数据库中:

 import java.util.Scanner;
import java.sql.*;


public class Program {


    public static void main(String[] args)throws ClassNotFoundException 


    {


        Connection conn=null;

        try {

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

             conn = DriverManager.getConnection("jdbc:mysql://localhost/DevOps_DB","root","root");


             PreparedStatement st = conn.prepareStatement("INSERT INTO pers " + "VALUES ('"+args[0]+"'); ");
             st.executeUpdate();


        } 



        catch (SQLException ex) {

            System.out.println("SQL Exception : "+ ex.getMessage());

            System.out.println("Vendor Error : "+ ex.getErrorCode());

        }


        catch(ClassNotFoundException ex) {

            ex.printStackTrace();


        }



//      
//      for(String arg : args)            
//      {   
//           System.out.println(arg);            
//      }




    }





}
Run Code Online (Sandbox Code Playgroud)

但我有以下例外:

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
    at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:323)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:268)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:190)
    at Program.main(Program.java:18)
Run Code Online (Sandbox Code Playgroud)

为什么 ?...有什么帮助解决这个问题吗?

编辑 :

我添加了.jar文件,见下图:

在此输入图像描述

Ani*_*kur 5

您需要下载mysql 连接器 jar文件(驱动程序实现)并将其添加到您的类路径中。

顺便说一句,如果您使用的是 JDBC 4.0(我认为是 Java 7 甚至 6),那么您不需要使用Class.forName("com.mysql.jdbc.Driver");. 只需将 jar 添加到类路径即可。驱动程序实现将自动从类路径中搜索并加载。