• Post author:
  • Post category:MySQL
  • Post last modified:May 30, 2024
  • Reading time:5 mins read

In this article, I will explain how to resolve the exception java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver. You would get this error at run time when Java unable to file the MySQL connector library in classpath. The com.mysql.cj.jdbc.Driver presents in the mysql-connector-java-*.jar.

Advertisements

Solution for java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver

You will get java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver exception or error when you run your Java program either from eclipse, IntelliJ, from the server, or docker container when MySQL connector Jar is missing in your classpath or dependencies.

As a first step, add the following dependency into your maven dependency and see if the problem is solved.


<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>8.0.13</version>
   <scope>runtime</scope>
</dependency>

If you are using Gradle, you can update the build.gradle file with the following.


buildscript {
    ext {
        ...
    }
    repositories {
        ...
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
        classpath('mysql:mysql-connector-java:8.0.13')
    }
 }

Solve from IntelliJ

You can also solve this problem by adding the jar to the classpath in IntelliJ, follow the below steps. You can down load the MySQL connector from https://mvnrepository.com/artifact/mysql/mysql-connector-java

  • Copy the MySQL jar somewhere on your system. (you can get it from .m2 repository)
  • Go to File > Project Structure.
  • Select Modules at the left panel and select the Dependencies tab.
  • Select the + icon and select 1 JARs or Directories option.
  • select your JAR file or you can select the directories.
  • Click on the OK button.

Solve from Eclipse

If you are using Eclipse then add the jar library manually to the project by following below steps.

Right Click the project — > build path — > configure build path

In the Libraries Tab press Add External Jar and Select your jar.

Add classpath

If you are running the Java program from the command line and you get this error java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver, you can use the -cp to add jars to classpath.


java -cp C:\path\to\your\jar\location\* YourJavaClass

Building the war with the Libraries

If you are using the web application then the war should contain the WEB-INF\lib folder with all the dependencies including MySQL connector.

Hope the solutions explained above solve your problem java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver

Conclusion

You would get java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver problem while running the Java application from Eclipse, IntelliJ when the MySQL connector is missing in your classpath.