首页 > 科技 > MySQL新版本驱动、时区设置serverTimezone

MySQL新版本驱动、时区设置serverTimezone

一、在datasource.url中设置serverTimezone

解决JDBC连接MySQL 8异常:java.sql.SQLException: The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone.

安装MySQL 8,同时驱动也改为了8.0.16

mysql

mysql-connector-java

8.0.16

这是由于数据库和系统时区差异所造成的系统时差引起,在jdbc连接的url后面加上参数serverTimezone=GMT可解决问题;如果使用GMT+8时区,需要对GMT+8转码,写成GMT%2B8。

常见的Timezone 设置:

  • UTC,世界均衡时间
  • GMT,格林尼治时间
  • 北京时间(东八区),GMT+8,url中表示为:&serverTimezone=GMT%2B8

我们一般认为GMT和UTC是一样的,都与英国伦敦的本地时间相同。

在datasource.url 属性设置时,可以参考如下设置:

spring.datasource.url=jdbc:mysql://localhost/database?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&useSSL=false

spring.datasource.username=root

spring.datasource.password=password

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

新版本mysql驱动为:com.mysql.cj.jdbc.Driver

如果使用老版本的mysql驱动:com.mysql.jdbc.Driver,项目启动会有提示:

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驱动。


二、MySQL的时区设置

MySQL的timestamp类型数据,存储的时候会转化成UTC时间戳,读取时再从UTC转化为本地时间戳。

查看当前全局时区和本次session时区:

show variables like '%time_zone%';

SELECT @@GLOBAL.time_zone, @@SESSION.time_zone;

设置全局时区:set global time_zone="+8:00"


本文来自投稿,不代表本人立场,如若转载,请注明出处:http://www.souzhinan.com/kj/266208.html