springboot连接mysql报错:com.mysql.jdbc.exceptions.jdbc4.CommunicationsException

nested exception is org.apache.ibatis.exceptions.PersistenceException: ### Error querying database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLNonTransientConnectionException: Could not create connection to database server. Attempted reconnect 3 times. Giving up. ### The error may exist in file [D:\JavaProject\dataservice\target\classes\mybatis\mapper\ClassificationMapper.xml] ### The error may involve com.tjhnode.dataservice.mapper.ClassificationMapper.findAll ### The error occurred while executing a query ### Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLNonTransientConnectionException: Could not create connection to database server. Attempted reconnect 3 times. Giving up.

出现此错误以为是连接超时,百度答案大多是修改mysql的my.ini配置文件,设置wait_timeout时长,但是并没有解决问题。

经过分析,首先我猜想是application.yml中无法使用localhost访问,于是修改修改mysql允许ip地址访问

1.进入mysql命令行,输入select host,user from mysql.user;

发现所有host字段均为localhost;

2.设置允许被任意IP地址访问,执行 update mysql.user set host = '%' where user = 'root';

然后执行  flush privileges;  刷新MySQL的系统权限相关表,客户端工具使用ip测试连接成功

重新运行项目,访问依旧报错,经过百度猜想大概是mysql驱动配置问题

3.修改application.yml中数据库连接配置,将localhost换成ip,另外,url 需要添加时区设置:&serverTimezone=UTC,

我使用的mysql版本是8.0.17,而mysql6.0以上对应的驱动要使用 com.mysql.cj.jdbc.Driver

spring:
datasource:
# 数据源基本配置
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.135.1:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC
type: com.alibaba.druid.pool.DruidDataSource

pom文件依赖

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>

重新运行,成功访问 http://localhost:8080/findAll

springboot连接mysql报错:com.mysql.jdbc.exceptions.jdbc4.CommunicationsException

上一篇:element-UI中table表格的row-click事件怎么获取一行数据的id


下一篇:老鸟的Python新手教程