MySQL8.0,免安装版的,配置成功后,在idea中进行连接,发现报错信息如下:1Connection to @localhost failed. [08001] Could not create connection to database server. Attempted reconnect 3 times. Giving up.
这实际上是mysql的url时区的陷阱:在使用mysql的6.0.x以上的jar的时候,需要在代码url的链接里面指定serverTimezone。否则就会出现异常。
***注意:mysql5.6版本出现这个问题时,在my.ini配置文档中添加:1default-time-zone = '+8:00'
即可解决!***
解决办法一(不推荐):
1.命令行登录MySQL1mysql -u root -p123456
2.修改MySQL时区1show variables like '%time_zone%'
这里是SYSTEM,时间不对需要修改,MySQL默认是美国时间,比我国要晚了8个小时,进行修改:1set global time_zone = '+8:00';
修改后,要退出MySQL,重新登录,查看修改结果:
发现修改成功。然后我们重新用idea连接MySQL,测试连接发现问题解决:
但是当MySQL服务重启的时候,会发现我们修改的时间被重置成立SYSTEM,问题依然存在,所以不推荐这种解决方法。
解决方法二:
实际上,当我们数据库连接失败的时候,意味着Java后台也无法正常连接数据库,会抛出异常:1Caused by: java.sql.SQLException: 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.
经历了一番查找,我们可以在IDEA中进行配置:
即将serverTimezone设置为UTC,问题得以解决!
在spring数据源配置中,添加:1jdbcUrl=jdbc:mysql://localhost:3306/spring?serverTimezone=UTC
异常得以解决!
注意:在后面跟多个配置项的时候要用;号隔开,如:1jdbcUrl=jdbc:mysql://localhost:3306/spring?serverTimezone=UTC&characterEncoding=utf-8
但UTC代表全球标准时间,Asia/Shanghai代表中国标准时间,所以要设置为serverTimezone=Asia/Shanghai
问题补充
MySQL8.0的连接池是com.mysql.cj.jdbc.Driver,之前5.7版本是com.mysql.jdbc.Driver
不得不记录下~避免再次入坑!!