You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Java连接MySQL数据库时出现错误,请求协助排查问题

Troubleshooting Your Java-MySQL Connection Issues

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) or brew services list (macOS with Homebrew) to verify.

5. Incorrect Credentials or Permissions

  • Confirm your root password is actually 1234—it's easy to mistype or forget you changed it.
  • Make sure the root user has permission to connect from localhost. You can check this in MySQL with:
    SELECT user, host FROM mysql.user WHERE user = 'root';
    
    If host isn't localhost or %, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:40:24