ClassNotFoundException in JDBC program despite of adding driver's JAR file

Viewed 263

I am writing a simple program in Java using to demonstrate insertion of data in MySQL table using JDBC. But the program is generating ClassNotFoundException while registering driver.

import java.sql.*;

public class test {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        }
        catch(ClassNotFoundException e) {
            System.out.println("ClassNotFoundException: "+e.getMessage());
        }
    }    
}

I have added the driver JAR file in the same directory.

To compile the program:

javac -cp ".:~/Programs/D/friends/assignment/driver.jar;" test.java

To execute the program:

java -cp ".:~/Programs/D/friends/assignment/driver.jar;" test

O/p:

ClassNotFoundException: com.mysql.jdbc.Driver

enter image description here

2 Answers

Note: The issue is caused by ; at the end of the driver.jar and also not using fully qualified path.

Windows based OS uses ; separator whereas Unix-based OS uses : separator.

Solution :

  1. First compile the code : javac test.java (Run this command)

  2. Run the code without semi-colon : java -cp .:<fully-qualified-path>/driver.jar test

Sample output :

anish@Anishs-MacBook-Pro ~ % javac Test.java
anish@Anishs-MacBook-Pro ~ % java -cp .:/Users/anish/driver.jar Test  
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

Note : I'm using mysql-connector-8.0.15.jar. If you are using the same or greater, then change from com.mysql.jdbc.Driver to com.mysql.cj.jdbc.Driver as that class is deprecated.

1.at the end of the classpath there seems to be an extra semi-colon:
/assignment/driver.jar;"
try without it

2. Are you sure driver.jar is the correct file?
normally they are called like mysql-connector-java-8.0.23.jar

Related