MySQL创建JDBC连接时区问题

报错内容

ErrorCode=0 
SQLState=01S00 
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的jdbc驱动最新版(6.0+)时,遇到数据库和系统时区差异引起的问题。

 

解决方法0-使用6.0以下版本的jdbc:

降版本,并不推荐;

 

解决方法1-在jdbc url指定默认时区:

还有一种是在jdbc连接的url后面加上serverTimezone=UTC或GMT即可,如果指定使用gmt+8时区,需要写成GMT%2B8,否则可能报解析为空的错误。示例如下:

jdbc.url=jdbc:mysql://localhost:3306/demo?serverTimezone=UTC

 

解决方法2-在数据库配置中添加默认时区:

方法1(该方法本人未实验成功):在my.cnf(linux)或者my.ini(win)配置文件[mysqld]底下添加: default-time-zone = '+8:00' 然后重启数据库服务器即可。

方法2:SQL语句配置全局时区

mysql> show variables like '%time_zone%';
+------------------+--------+
| Variable_name    | Value  |
+------------------+--------+
| system_time_zone |        |
| time_zone        | SYSTEM |
+------------------+--------+
2 rows in set, 1 warning (0.00 sec)

#设置当前session时区,即时生效,但仅作用于当前session
mysql> set time_zone='+8:00';
Query OK, 0 rows affected (0.00 sec)

#设置全局时区,即时生效,作用于所有session
mysql> set global time_zone='+8:00';
Query OK, 0 rows affected (0.00 sec)

mysql> show variables like '%time_zone%';
+------------------+--------+
| Variable_name    | Value  |
+------------------+--------+
| system_time_zone |        |
| time_zone        | +08:00 |
+------------------+--------+
2 rows in set, 1 warning (0.00 sec)

 

转载于:https://my.oschina.net/liuyuanyuangogo/blog/2413468