使用Java连接MySQL数据库时出现错误,请求协助排查问题
Let's break down the possible problems in your code and how to fix them. First, here's your original code for reference:
package dbb; import java.sql.*; public class test { public static void main (String[] args) { String url = "jdbc:mysql://localhost:3306/test"; String user = "root"; String pass = "1234"; Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); System.out.println("Driver Searched"); conn = DriverManager.getConnection(url, user, pass); System.out.println("Connection Succeed" + conn); } catch (ClassNotFoundException e) { System.out.println("Driver Not Searched"); e.printStackTrace(); } // Note: Your code cuts off here, likely missing SQLException handling } }
Common Causes & Fixes
1. Mismatched JDBC Driver Class Name (Version Conflict)
If you're using MySQL 8.0 or newer, the old driver class com.mysql.jdbc.Driver is deprecated. You need to switch to the updated class:
Class.forName("com.mysql.cj.jdbc.Driver");
Pro tip: Starting from MySQL 8.0, you don't even need Class.forName() anymore—JDBC 4.0+ automatically loads the driver if it's in your classpath. You can safely remove that line if you want.
2. Missing MySQL JDBC Driver Dependency
You probably haven't added the MySQL JDBC driver to your project. Here's how to fix it:
- Maven Project: Add this to your
pom.xml:<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.33</version> <!-- Use the latest stable version --> </dependency> - Gradle Project: Add this to your
build.gradle:implementation 'mysql:mysql-connector-java:8.0.33' - Manual JAR Import: Download the driver JAR from MySQL's official site and add it to your project's classpath.
3. Missing URL Parameters (Critical for MySQL 8.0+)
MySQL 8.0 requires you to specify a timezone in the JDBC URL, otherwise you'll get a timezone-related error. Update your URL like this:
String url = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC";
Or use your local timezone (e.g., Asia/Shanghai if you're in China).
4. MySQL Service Isn't Running
Double-check that your local MySQL server is up and running:
- On Windows: Go to Services (search "Services" in Start Menu) and make sure "MySQL" is set to "Running".
- On Linux/macOS: Run
sudo systemctl status mysql(Linux) orbrew services list(macOS with Homebrew) to verify.
5. Incorrect Credentials or Permissions
- Confirm your
rootpassword is actually1234—it's easy to mistype or forget you changed it. - Make sure the
rootuser has permission to connect fromlocalhost. You can check this in MySQL with:
IfSELECT user, host FROM mysql.user WHERE user = 'root';hostisn'tlocalhostor%, you'll need to grant access:GRANT ALL PRIVILEGES ON test.* TO 'root'@'localhost' IDENTIFIED BY '1234'; FLUSH PRIVILEGES;
6. Incomplete Exception Handling
Your current code only catches ClassNotFoundException, but DriverManager.getConnection() can throw SQLException. Add a catch block for it to get more detailed error messages:
catch (SQLException e) { System.out.println("Connection Failed"); e.printStackTrace(); }
Fixed Code Example
Here's your code with all the above fixes applied:
package dbb; import java.sql.*; public class test { public static void main (String[] args) { String url = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC"; String user = "root"; String pass = "1234"; Connection conn = null; try { // Optional for MySQL 8.0+ // Class.forName("com.mysql.cj.jdbc.Driver"); System.out.println("Driver Loaded (if needed)"); conn = DriverManager.getConnection(url, user, pass); System.out.println("Connection Succeed: " + conn); } catch (ClassNotFoundException e) { System.out.println("Driver Not Found"); e.printStackTrace(); } catch (SQLException e) { System.out.println("Connection Failed"); e.printStackTrace(); } finally { // Always close the connection when done try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
Run this code, and if you still get errors, check the stack trace—it will tell you exactly what's wrong (e.g., access denied, timezone issue, etc.).
内容的提问来源于stack exchange,提问作者garden lee

