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

蹲街弑〆低调 提交于 2021-02-16 14:20:51

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/66060341/classnotfoundexception-in-jdbc-program-despite-of-adding-drivers-jar-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!