欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

mysql中url时区的陷阱该如何规避详解

程序员文章站 2022-06-14 15:13:58
前言 最近在使用mysql的6.0.x以上的jar的时候,需要在代码url的链接里面指定servertimezone。就会出现异常: 1.未指定servertime...

前言

最近在使用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
中国标准时间

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对的支持。