数据库连接问题解决方案.md 4.0 KB

数据库连接问题解决方案

问题描述

错误:Communications link failureConnection timed out

解决方案

方案1:使用本地数据库(推荐)

如果你的MySQL安装在本地,修改 application.yml 中的数据库地址为:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/book?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
    username: root
    password: 你的密码

方案2:使用远程数据库(如果必须使用 192.168.254.101)

2.1 检查网络连接

在命令行执行:

ping 192.168.254.101

如果ping不通,说明网络不通。

2.2 检查MySQL服务是否运行

在远程服务器上检查:

# Linux
systemctl status mysql
# 或
systemctl status mysqld

2.3 检查MySQL是否允许远程连接

在远程MySQL服务器上执行:

  1. 登录MySQL:

    mysql -u root -p
    
  2. 检查用户权限:

    SELECT host, user FROM mysql.user WHERE user='root';
    
  3. 如果host是localhost,需要允许远程连接:

    -- 允许root用户从任何IP连接(不安全,仅用于测试)
    GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '你的密码' WITH GRANT OPTION;
    FLUSH PRIVILEGES;
    
    -- 或者只允许特定IP
    GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.%.%' IDENTIFIED BY '你的密码' WITH GRANT OPTION;
    FLUSH PRIVILEGES;
    
  4. 检查MySQL配置文件(my.cnf 或 my.ini):

    # 确保bind-address不是127.0.0.1
    bind-address = 0.0.0.0
    # 或者注释掉
    # bind-address = 127.0.0.1
    

2.4 检查防火墙

在远程服务器上开放3306端口:

Linux (firewalld):

sudo firewall-cmd --permanent --add-port=3306/tcp
sudo firewall-cmd --reload

Linux (iptables):

sudo iptables -A INPUT -p tcp --dport 3306 -j ACCEPT

Windows:

  • 控制面板 -> Windows Defender防火墙 -> 高级设置
  • 添加入站规则,允许3306端口

方案3:测试数据库连接

创建一个简单的测试类来验证连接:

import java.sql.Connection;
import java.sql.DriverManager;

public class TestConnection {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/book?useSSL=false&serverTimezone=Asia/Shanghai";
        String username = "root";
        String password = "你的密码";
        
        try {
            Connection conn = DriverManager.getConnection(url, username, password);
            System.out.println("数据库连接成功!");
            conn.close();
        } catch (Exception e) {
            System.out.println("数据库连接失败:" + e.getMessage());
            e.printStackTrace();
        }
    }
}

方案4:使用不同的数据库地址

如果192.168.254.101是远程服务器,尝试:

  1. 使用服务器名称(如果配置了hosts):

    url: jdbc:mysql://your-server-name:3306/book?...
    
  2. 使用127.0.0.1(如果数据库在本地):

    url: jdbc:mysql://127.0.0.1:3306/book?...
    

常见问题排查

  1. 确认数据库已创建

    CREATE DATABASE IF NOT EXISTS book CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
    
  2. 确认已执行SQL脚本 确保已执行 d:\桌面\book.sql 创建表结构

  3. 检查密码是否正确

    • 确认密码没有多余空格
    • 确认密码是否包含特殊字符需要转义
  4. 检查时区设置 如果还有问题,尝试:

    url: jdbc:mysql://localhost:3306/book?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
    

快速修复步骤

  1. 如果是本地数据库

    • 修改 application.yml 中的 urllocalhost:3306
    • 确认数据库密码正确
  2. 如果是远程数据库

    • 先测试网络:ping 192.168.254.101
    • 测试端口:telnet 192.168.254.101 3306
    • 检查MySQL远程连接配置
    • 检查防火墙设置
  3. 重启应用: 修改配置后,重启Spring Boot应用