记录因为yml而产生的坑:java.sql.SQLException: Access denied for user ‘root‘@‘localhost‘ (using password: YES)

我们在使用springboot连接数据库时,可能有些会用yml来设置DataSource信息,那么可能会出现以下异常:

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

日志显示, 密码错误, 但是你多次尝试发现自己的用户名和密码都是没有问题的, 所以令你百思不得其解.

其实这是yml文件的规定, 在使用字符串时需要加双引号, 而这里我们的password其实就是字符串, 但是在application.yml文件中, 我们并没有对密码加双引号.

# spring的配置
spring:
  application:
    name: springcloud-provider-dept
    #数据源的配置
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springclouddb01?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false
    username: root
    password: 123456 

在这里只需要把password用双引号括起来就行了

# spring的配置
spring:
  application:
    name: springcloud-provider-dept
    #数据源的配置
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springclouddb01?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false
    username: root
    password: "123456"   

之后就允许正常了.

拓展: 

当然了, 除了采用application.yml格式的文件, 还有很多开发者会采用application.properties格式的文件, 但是这种文件并没有规定字符串需要加上双引号. 所以它直接写也是不会报错的.

#服务器的端口号
server.port=80

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://119.23.248.141:3306/wolf?characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456

猜你喜欢

转载自blog.csdn.net/m0_50370837/article/details/126164976