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

<dependency>

<groupid>mysql/<groupid>

<artifactid>mysql-connector-java/<artifactid>

<version>8.0.16/<version>

這是由於數據庫和系統時區差異所造成的系統時差引起,在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%';

MySQL新版本驅動、時區設置serverTimezone

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

MySQL新版本驅動、時區設置serverTimezone

設置全局時區:set global time_zone="+8:00"



分享到:


相關文章: