MySQL| 如何规避mysql的url时区的陷阱?

前言

最近项目使用的MySQL5.6迁移到了MySLQ8,以前一直用的是这两个版本都兼容的驱动包mysql-connector-java.5.1.x.jar,么有出现任何问题,
在这里插入图片描述
今天偶然部署应用的时候使用的是8的驱动包
在这里插入图片描述
结果启动项目时出现是去问题:

Caused by: com.mysql.cj.core.exceptions.InvalidConnectionAttributeException: 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.

在使用mysql的6.0.x以上的jar的时候,需要在代码url的链接里面指定serverTimezone。就会出现异常

1.未指定serverTimezone

  • xml里面配置url
<property name="url" value="jdbc:mysql://localhost:3306/mybatisstudy"/>
  • 出现的异常
Caused by: com.mysql.cj.core.exceptions.InvalidConnectionAttributeException: 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.

您必须配置服务器或JDBC驱动程序(通过serverTimezone配置属性),如果您想要使用时区支持,则需要使用一个更详细的时区值。

2.网上的解决方案

  • 在url后面加上参数?serverTimezone=utc
<property name="url" value="jdbc:mysql://localhost:3306/springdatastudy?serverTimezone=UTC"/>
2.1.遇到的问题

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

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

但是在数据库里面显示的时间却为:2017-08-21 09:29:56

3.根本原因

因为时区设置的问题。

UTC代表的是全球标准时间 ,但是我们使用的时间是北京时区也就是东八区,领先UTC八个小时。

UTC + (+0800) = 本地(北京)时间

4.解决方案

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

4.1 使用java代码获取本地的时区id
Calendar cal = Calendar.getInstance();
TimeZone timeZone = cal.getTimeZone();
System.out.println(timeZone.getID());
System.out.println(timeZone.getDisplayName());
Asia/Shanghai
中国标准时间

5.中文乱码的解决方案

url链接后面加上编码字符 characterEncoding=utf8

jdbc.url=jdbc:mysql://localhost:3306/cnblogs?serverTimezone=Asia/Shanghai&characterEncoding=utf8


参考:
https://www.jianshu.com/p/7e9247c0b81a

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值