mysql出现The server time zone value '�й���׼ʱ��' is unrecogni的解决方法

今天心血来要搞一个SpringBoot整合Mybatis的框架,在访问Controller的时候,最不想看到的报错信息出现了 ↓

java.sql.SQLException: The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129) ~[mysql-connector-java-8.0.17.jar:8.0.17]
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.17.jar:8.0.17]
......

 经过测试,发现使用SpringBoot2.1.0以下的版本是不会报这个错误的!!!

接下来上网查找解决方案,发现是我的配置文件application.yml中数据库url地址的问题。

SpringBoot 2.0.1版本配置如下:

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/sakila?useUnicode=true&characterEncoding=UTF-8
    driver-class-name: com.mysql.jdbc.Driver

mybatis:
  type-aliases-package: com.utry.entity
  mapper-locations: classpath:mapper/*Mapper.xml

查询到的解决方案如下:(猜测估计是因为SpringBoot 2.1.x版本使用的的jdbc驱动是6.0版本以上吧)

引用连接:https://blog.csdn.net/weixin_43400357/article/details/97916822

原因是因为使用了Mysql Connector/J 6.x以上的版本,然后就报了时区的错误

遇到的问题 servertime=UTC导致时间差8个小时(

MySQL jdbc 6.0 版本以上必须配置此参数

解决办法: 
在配置url的时候不能简单写成 :jdbc:mysql://localhost:3306/mysql
而是要写成 :jdbc:mysql://localhost:3306/mysql?serverTimezone=UTC

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/sakila?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
  type-aliases-package: com.utry.entity
  mapper-locations: classpath:mapper/*Mapper.xml

虽然上面加上时区程序不出错了,但是我们在用java代码插入到数据库时间的时候却出现了问题。

比如在java代码里面插入的时间为:2017-08-21 17:29:56

但是在数据库里面显示的时间却为:2017-08-21 09:29:56
因为时区设置的问题。
UTC代表的是全球标准时间 ,但是我们使用的时间是北京时区也就是东八区,领先UTC八个小时。

UTC + (+0800) = 本地(北京)时间
解决方案:

url的时区使用中国标准时间。也是就 serverTimezone=Asia/Shanghai

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/sakila?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
  type-aliases-package: com.utry.entity
  mapper-locations: classpath:mapper/*Mapper.xml

至此完美解决!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值