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,

