IntelliJ/PyCharm:连接到本地主机 MySQL 失败

IntelliJ/PyCharm: Connection to localhost MySQL failed

我正在使用 PyCharm 在本地主机端口 3306 连接到我的本地 MySQL 数据库 运行。这是我的 JDBC url 在 "Data Sources and Drivers" window 如图所示 PyCharm:

jdbc:mysql://localhost:3306/mydb

当我尝试连接或单击 "Test Connection" 我在 IntelliJ 中收到此错误:

Error: Connection to MySQL failed.

Connection to Local MySQL failed.
[08S01] Communications link failure.
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

我可以使用命令行客户端连接到 mysql,只是 PyCharm 不工作。我做错了什么?

确保您的 MySQL 没有侦听 IPv6 地址。由于某些原因 IntelliJ/PyCharm 在连接到 MySQL 运行 的 IPv6 地址时出现问题。

要查看您的 MySQL 服务器正在侦听的地址,请键入:

$ ss -ntl|grep 3306 
LISTEN      0      80       [::1]:3306                  [::]:*

[::1]:3306 部分表示它正在侦听本地主机上的 IPv6 地址。

要更改为 IPv4,打开 /etc/mysql/my.cnf 和 add/set [mysqld] 部分中的 bind-address 参数为 127.0.0.1 而不是 localhost

...
[mysqld]
...
port = 3306
bind-address = 127.0.0.1
...

然后重新启动 mysqld.service,您就可以通过 IntelliJ/PyCharm 连接了。