今天遇到個問題,使我們OA報的錯誤,連接MySQL的數據源不行了,不知道為啥,后臺日志是這樣的。
Caused by: com.mysql.cj.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.
at sun.reflect.GeneratedConstructorAccessor520.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:59)
at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:83)
at com.mysql.cj.util.TimeUtil.getCanonicalTimezone(TimeUtil.java:128)
at com.mysql.cj.protocol.a.NativeProtocol.configureTimezone(NativeProtocol.java:2201)
at com.mysql.cj.protocol.a.NativeProtocol.initServerSession(NativeProtocol.java:2225)
at com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:1391)
at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:993)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:852)
看這個描述吧,像是時區什么的問題,但是我就是創建個數據源,和時間還有關?
然后我就開始了百度,找到了一些文章,還真是時區的問題。
解決方案
既然是時區的問題,那就有幾種方式來修改,
1個是直接修改配置文件,但是需要重啟服務:
在my.ini文件中,在[mysqld]下,增加時區配置
# Set default time zone
default-time-zone = '+08:00'
另一種方案是通過SQL在線修改,但是重啟服務后會失效
set global time_zone='+8:00';
flush privileges;
我們可以通過命令查看當前的參數配置:
show variables like '%time_zone%';
沒修改之前,我這里顯示的是SYSTEM
如果是代碼或者工具配置,可以通過修改URL的方式來解決,就是增加時區的參數
jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC
jdbc:mysql://localhost/db?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
修改完之后,記得使用 select now() 來測試下
select now();