错误:Communications link failure 和 Connection timed out
如果你的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: 你的密码
在命令行执行:
ping 192.168.254.101
如果ping不通,说明网络不通。
在远程服务器上检查:
# Linux
systemctl status mysql
# 或
systemctl status mysqld
在远程MySQL服务器上执行:
登录MySQL:
mysql -u root -p
检查用户权限:
SELECT host, user FROM mysql.user WHERE user='root';
如果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;
检查MySQL配置文件(my.cnf 或 my.ini):
# 确保bind-address不是127.0.0.1
bind-address = 0.0.0.0
# 或者注释掉
# bind-address = 127.0.0.1
在远程服务器上开放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:
创建一个简单的测试类来验证连接:
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();
}
}
}
如果192.168.254.101是远程服务器,尝试:
使用服务器名称(如果配置了hosts):
url: jdbc:mysql://your-server-name:3306/book?...
使用127.0.0.1(如果数据库在本地):
url: jdbc:mysql://127.0.0.1:3306/book?...
确认数据库已创建
CREATE DATABASE IF NOT EXISTS book CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
确认已执行SQL脚本
确保已执行 d:\桌面\book.sql 创建表结构
检查密码是否正确
检查时区设置 如果还有问题,尝试:
url: jdbc:mysql://localhost:3306/book?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
如果是本地数据库:
application.yml 中的 url 为 localhost:3306如果是远程数据库:
ping 192.168.254.101telnet 192.168.254.101 3306重启应用: 修改配置后,重启Spring Boot应用