今天在使用spring boot整合MySQL时一直报“java.sql.SQLException: The server time zone value ‘Öйú±ê׼ʱ¼ä’ is unrecognized or represents more…”这样的错误,一直很困扰,之前怎么都没有报错,通过上网查看终于找到了答案,在此整理一下:
部分报错信息如下:
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.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
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:61)
at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:85)
at com.mysql.cj.util.TimeUtil.getCanonicalTimezone(TimeUtil.java:132)
at com.mysql.cj.protocol.a.NativeProtocol.configureTimezone(NativeProtocol.java:2234)
at com.mysql.cj.protocol.a.NativeProtocol.initServerSession(NativeProtocol.java:2258)
at com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:1319)
at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:966)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:825)
... 64 more
上网查询了一下,原来是MySQL和本地时区不同的原因,网上最多的解决方法:
- 用命令修改数据库时区;
- 修改MySQL的.ini文件。
但我觉得这些都不应该是我要找的答案,因为我之前搭建或开发项目也没有出现这样的问题,所以不应该是数据库的问题,终于,在这篇文章中受到了启发,这篇文章说mysql-connector-java 6.x版本会出现时间差的问题,吓得我赶紧去看看自己的jar包版本,不看不知道一看吓一跳,由于pom文件中没有指定具体版本,才发现它自动为我引用了8.0的版本(而我之前一直使用的是5.*),找到问题的原因就好办了,我试了两种方案:
- 修改pom文件,使用低版本5.*;
- 使用8.0的高版本,然后在jdbc连接、驱动中添加&serverTimezone=UTC。
问题的确被成功解决了。