MySQL JDBC数据库连接报错咨询:Error:com.mysql.jdbc.driver
Alright, let's figure out why you're getting that Error:com.mysql.jdbc.driver message and fix it up step by step!
The biggest issue here is a simple typo: the MySQL JDBC driver's fully qualified class name is com.mysql.jdbc.Driver, with a capitalized 'D' at the end. Your code uses lowercase driver, which Java can't find—since class names are case-sensitive in Java. That's almost certainly why you're seeing the error right now.
Even if you fix the typo, you'll still get this error if your project doesn't have the MySQL connector JAR file included:
- For a plain Java project: Download the appropriate
mysql-connector-javaJAR, then add it to your project's build path (in Eclipse/IntelliJ, right-click the project > Build Path > Add External Archives). - For a Maven project, add this dependency to your
pom.xml(use a version that matches your MySQL server version):<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.33</version> <!-- Adjust to your MySQL version --> </dependency>
There's a key change between MySQL 5.x and 8.x that affects the driver class:
- If you're using MySQL 5.x, stick with
com.mysql.jdbc.Driverand use a 5.x version of the connector. - If you're using MySQL 8.0 or newer, the driver class has changed to
com.mysql.cj.jdbc.Driver. You'll also need to include a timezone parameter in your JDBC URL later (likejdbc:mysql://localhost:3306/your_db?serverTimezone=UTC).
Here's your code fixed with the proper class name, plus notes for MySQL 8.x:
import java.sql.*; public class NewClass { public static void main(String args[]) { try { // For MySQL 5.x: Correct capitalized Driver class name Class.forName("com.mysql.jdbc.Driver"); // Uncomment this line instead if using MySQL 8.x+ // Class.forName("com.mysql.cj.jdbc.Driver"); System.out.println("JDBC Driver loaded successfully!"); } catch (ClassNotFoundException ex) { System.out.println("Error:" + ex.getMessage()); } catch (Exception ex) { ex.printStackTrace(); } } }
Quick side note: Starting with JDBC 4.0, you don't even need to call Class.forName() anymore—Java will automatically load drivers that are in the classpath. But if you prefer to keep that line, just make sure the class name is correct.
内容的提问来源于stack exchange,提问作者Akshat Daxini

