尽管添加了驱动程序的JAR文件,JDBC程序中的ClassNotFoundException [英] ClassNotFoundException in JDBC program despite of adding driver's JAR file
问题描述
我正在用Java编写一个简单的程序,用来演示使用JDBC在MySQL表中插入数据.但是程序在注册驱动程序时会生成ClassNotFoundException.
import java.sql.*;公开课测试{公共静态void main(String [] args){尝试 {Class.forName("com.mysql.jdbc.Driver");}catch(ClassNotFoundException e){System.out.println("ClassNotFoundException:" + e.getMessage());}}}
我已经在同一目录中添加了驱动程序JAR文件.
要编译程序:
javac -cp.:〜/Programs/D/friends/assignment/driver.jar;"test.java
要执行程序,请执行以下操作:
java -cp.:〜/Programs/D/friends/assignment/driver.jar;"测试
O/p:
ClassNotFoundException:com.mysql.jdbc.Driver
注意:该问题是由driver.jar末尾的; 引起的,但不是使用完全限定的路径.
基于Windows的操作系统使用; 分隔符,而基于Unix的操作系统使用:分隔符.
解决方案:
-
首先编译代码:
javac test.java
(运行此命令) -
运行不带分号的代码:
java -cp.:<完全限定路径>/driver.jar测试
样本输出:
anish @ Anishs-MacBook-Pro〜%javac Test.javaanish @ Anishs-MacBook-Pro〜%java -cp.:/Users/anish/driver.jar测试加载类"com.mysql.jdbc.Driver".不推荐使用.新的驱动程序类为"com.mysql.cj.jdbc.Driver".通过SPI自动注册驱动程序,通常不需要手动加载驱动程序类.
注意::我正在使用 mysql-connector-8.0.15.jar .如果使用相同或更大的版本,则在不赞成使用该类的情况下,从 com.mysql.jdbc.Driver
更改为 com.mysql.cj.jdbc.Driver
./p>
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
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 :
First compile the code :
javac test.java
(Run this command)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.
这篇关于尽管添加了驱动程序的JAR文件,JDBC程序中的ClassNotFoundException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!