IDEA连接MySQL8.0数据库时,报错[08001] Could not create connection to database server. Attempted reconnect 3 times. Giving up.

1、Bug复现

最近,使用easyCode工具逆向生成时,连接数据库时,一直报错,出现连接失败(我的MySQL数据库版本为8.0版本,5.0及以上版本未发现此问题)。

报错信息如下:

Connection to @localhost failed. 
[08001] Could not create connection to database server. Attempted reconnect 3 times. Giving up.

2、问题原因

刚开始由于要急切连接上数据库,所以,就查找了一个解决方案,说是在IDEA连接数据库界面的URL后面,添加下面配置:

?serverTimezone=GMT

IDEA连接MySQL8.0数据库时,报错[08001] Could not create connection to database server. Attempted reconnect 3 times. Giving up.

添加完上面配置之后,的确解决了燃眉之急,但是这样做,有一个弊端,就是每次都要添加,所以为了从根本上解决,就抽时间查找了一下具体原因。

出现这种问题的原因就是:系统默认的时区与IDEA连接数据库的时区 (MySQL默认时区为UTC) 不一致,

按照格林威治的时间,我们属于东八区时间,领先UTC八个小时,所以说存在8小时的时差。

查找到这个原因之后,特意查看了一下MySQL的时区,具体操作如下:

IDEA连接MySQL8.0数据库时,报错[08001] Could not create connection to database server. Attempted reconnect 3 times. Giving up.

3、问题解决

知道原因之后,就进行解决吧,针对这个问题,网上有以下解决方案,这里都贴上,仅供参考。

方案1:
在mysql的命令模式下,输入:set global time_zone='+8:00';
不过,这种方式,mysql服务启动每启动一次,就要重新输入一次!!!
方案2:
在MySQL安装目录下找到my.ini文件并打开,
在[mysqld]下添加一行  default-time-zone='+08:00'
然后,保存文件,重启MySQL数据库服务

IDEA连接MySQL8.0数据库时,报错[08001] Could not create connection to database server. Attempted reconnect 3 times. Giving up.

重启MySQL服务之后,查看修改之后的时区值,如下:

IDEA连接MySQL8.0数据库时,报错[08001] Could not create connection to database server. Attempted reconnect 3 times. Giving up.

方案3:
在IDEA上连接数据库时,修改 Advanced 中 serverTimezone 的属性值为 Asia/Shanghai

IDEA连接MySQL8.0数据库时,报错[08001] Could not create connection to database server. Attempted reconnect 3 times. Giving up.

方案4:
降低MySQL数据库驱动的版本,这里我的MySQL数据库版本为8.0版本,可以降级到5.0及以上的版本,也可以解决这个问题

IDEA连接MySQL8.0数据库时,报错[08001] Could not create connection to database server. Attempted reconnect 3 times. Giving up.