Java连接MySQL数据库报错:找不到com.mysql.jdbc.Driver驱动类
解决Java连接MySQL时的ClassNotFoundException(com.mysql.jdbc.Driver)
报错信息
Error loading MySQL driver: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
问题代码
import java.sql.*; public class Javaconnect { public static void main(String[] args) throws SQLException { Connection connection = null; try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/lol", "root", "lol@9056"); } catch (ClassNotFoundException e) { System.out.println("Error loading MySQL driver: " + e); } if (connection != null) { System.out.println("Established connection"); connection.close(); } } }
解决方案
添加MySQL JDBC驱动依赖
该错误本质是项目类路径中缺失MySQL驱动包,根据你的构建方式选择对应操作:- 手动引入:下载对应版本的MySQL Connector/J jar包,放到项目lib目录,并在IDE中添加为项目库(比如IDEA右键jar包选「Add as Library」)。
- Maven项目:在
pom.xml中加入依赖(示例为MySQL 8.x版本):<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.33</version> </dependency> - Gradle项目:在
build.gradle中加入:implementation 'mysql:mysql-connector-java:8.0.33'
匹配驱动类名与MySQL版本
- MySQL 5.x及更早版本:驱动类用
com.mysql.jdbc.Driver - MySQL 8.x及更新版本:驱动类需改为
com.mysql.cj.jdbc.Driver,同时JDBC URL要补充时区参数,示例:jdbc:mysql://localhost:3306/lol?useSSL=false&serverTimezone=UTC
- MySQL 5.x及更早版本:驱动类用
验证类路径配置
若手动添加jar包,确认IDE已将其纳入编译和运行的类路径,避免编译通过但运行时找不到类的情况。
内容的提问来源于stack exchange,提问作者ITACHI Uchiha
相关产品推荐
相关产品推荐

