Pymysql 无法连接 MySQL 数据库:挂在 "self.sock.recv_into(b)"?

Pymysql can't connect do MySQL DB: hangs at "self.sock.recv_into(b)"?

目前在 macOS 10.15 上使用 python 3.7,安装了 MySQL 8.0.19。使用虚拟环境设置在 VScode 中开发。我也在 phpmyadmin 中创建了一个本地数据库。我想尽可能地连接到它。脚本:

import pymysql

print("Before")
connection = pymysql.connect(host='localhost',
    user='myUserName', password='myPassword', db='db_name', charset='utf8mb4', 
          cursorclass=pymysql.cursors.DictCursor)
print("After")

当我 运行 脚本时,执行无限期挂起。打印完"After",只好退出执行。引用是:

Traceback (most recent call last):
File "connect.py", line 5, in <module>
  user='myUserName', password='myPassword', db='db_name', charset='utf8mb4', 
  cursorclass=pymysql.cursors.DictCursor)
File "/Users/name/Documents/Work/Connection Test/env/lib/python3.7/site- 
  packages/pymysql/__init__.py", line 94, in Connect
  return Connection(*args, **kwargs)
File "/Users/name/Documents/Work/Connection Test/env/lib/python3.7/site- 
  packages/pymysql/connections.py", line 325, in __init__
  self.connect()
File "/Users/name/Documents/Work/Connection Test/env/lib/python3.7/site- 
  packages/pymysql/connections.py", line 598, in connect
  self._get_server_information()
File "/Users/name/Documents/Work/Connection Test/env/lib/python3.7/site- 
  packages/pymysql/connections.py", line 975, in _get_server_information
  packet = self._read_packet()
File "/Users/name/Documents/Work/Connection Test/env/lib/python3.7/site- 
packages/pymysql/connections.py", line 657, in _read_packet
  packet_header = self._read_bytes(4)
File "/Users/name/Documents/Work/Connection Test/env/lib/python3.7/site- 
  packages/pymysql/connections.py", line 691, in _read_bytes
  data = self._rfile.read(num_bytes)
File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/
python3.7/socket.py", line 589, in readinto
  return self._sock.recv_into(b)
KeyboardInterrupt

不知道为什么会这样。这里发生了什么?我搜索了大量关于堆栈溢出的问题,none 帮助了我。

通过在 pymysql 连接函数中添加“unix_socket”参数解决了问题。在这里查看答案:pymysql can't connect to MySQL on localhost

import pymysql

print("Before")
conn = pymysql.connect(db='w_dev', user='root', passwd='celebrate', 
unix_socket="/tmp/mysql.sock")
print("After")

这个脚本有效。