Home >Java >javaTutorial >How to Resolve java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in MySQL Connector/J?

How to Resolve java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in MySQL Connector/J?

Linda Hamilton
Linda HamiltonOriginal
2024-12-27 07:58:10469browse

How to Resolve java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in MySQL Connector/J?

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver MySQLConnector/J

Problem:
When compiling a Java program that connects to a MySQL database, the code throws a "java.lang.ClassNotFoundException: com.mysql.jdbc.Driver".

Cause:
This error occurs when the MySQL connector JAR file (mysql-connector-java.jar) is not properly included in the Java application's dependencies.

Solution:

Maven Projects:

  • Add the MySQL connector dependency to the Maven POM file:
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.39</version>
</dependency>

Non-Maven Projects:

  • Manually add the MySQL connector JAR file to the project build path:
  1. Right-click on the project in the IDE.
  2. Select "Build Path" -> "Configure Build Path".
  3. In the "Libraries" tab, click "Add External JARs".
  4. Browse and select the mysql-connector-java.jar file.

Explanation:
The "java.lang.ClassNotFoundException" exception is thrown when the Java Virtual Machine cannot find the specified class. In this case, it's unable to locate the "com.mysql.jdbc.Driver" class, which is part of the MySQL JDBC driver library. When the MySQL connector JAR is not included in the project dependencies, the virtual machine cannot find the class and throws this error. By adding the JAR file to the dependencies, the virtual machine will be able to locate the required class and the application will successfully connect to the database.

The above is the detailed content of How to Resolve java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in MySQL Connector/J?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn