Failed|Failed to obtain JDBC Connection; nested exception

author: Nathannie
date: 2022-03-26-23:29
问题背景 spingboot整合mybatis过程中启动spingboot报错。
报错信息 【Failed|Failed to obtain JDBC Connection; nested exception】报错内容:

org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException: ### Error querying database.Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: Access denied for user '***'@'localhost' (using password: YES) ### The error may exist in com/itheima/springbootmybatis/mapper/UserMapper.java (best guess) ### The error may involve com.itheima.springbootmybatis.mapper.UserMapper.findAll ### The error occurred while executing a query ### Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: Access denied for user '***'@'localhost' (using password: YES)

报错定位: ### Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: Access denied for user '***'@'localhost' (using password: YES)
问题分析 报错内容含义: 获取数据库连接失败 Access denied for user '*'@'localhost' (using password: YES)
可能的原因
1、书写错误。数据库连接url的jdbc写成了jbdc。检查数据库连接配置是否正确,用户名,密码,连接地址等。
2、时区问题。mysql驱动版本和系统时区不一致
新发现的问题
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

mysql版本问题
8.0以后的版本使用com.mysql.cj.jdbc.Driver驱动,添加了cj包。不过继续使用com.mysql.jdbc.Driver也没有报错,严谨考虑还是写全cj。
问题解决 本次报错原因: 时区问题
使用的数据库是MySQL,驱动是8.0.18,这是由于数据库和系统时区差异所造成的,在jdbc连接的url后面加上serverTimezone=GMT即可解决问题[1],如果需要使用gmt+8时区,需要写成GMT%2B8,否则会被解析为空。再一个解决办法就是使用低版本的MySQL jdbc驱动,5.1.28不会存在时区的问题。
将配置文件中连接数据源操作url后添加serverTimezone=GMT
spring: datasource: url: jdbc:mysql:///springboot?serverTimezone=GMT username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver

相关参考
  • https://blog.csdn.net/wxb1410...
  • https://blog.csdn.net/liangll...

    推荐阅读