PyMySQL 使用 localhost 与 socket 不一致的行为
PyMySQL using localhost vs socket incoherant behaviour
我正在使用 PyMySQL to connect to a database running on localhost. I can access the database just fine using the username/password combiunation in both the command line and adminer 所以数据库似乎不是这里的问题。
我的代码如下。但是,当 使用 host="127.0.0.1"
选项时,我得到一个 OperationalError
和一个 Errno 111
。 使用相同的代码,但通过套接字连接 Mariadb 运行开就好了。
import pymysql.cursors
from pprint import pprint
# This causes an OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)")
# connection = pymysql.connect(
# host="127.0.0.1",
# port=3306,
# user="root",
# password="S3kr37",
# db="my_test",
# )
# This works.
connection = pymysql.connect(
user="root",
password="S3kr37",
db="my_test",
unix_socket="/var/lib/mysql/mysql.sock"
)
try:
with connection.cursor() as cursor:
sql = "select * from MySuperTable"
cursor.execute(sql)
results = cursor.fetchall()
pprint(results)
finally:
connection.close()
我做错了什么?
PS:请注意this question也有同样的问题,但提供的解决方案是套接字。 不够好: 我想知道为什么 我不能按照文档中的建议使用主机名。
客户端库返回错误代码 2003 (CR_CONN_HOST_ERROR),以防客户端无法与服务器建立 tcp 连接。
首先你应该检查,如果你可以通过 telnet 或 mysql 命令行客户端连接到你的服务器。
如果没有,检查服务器配置文件:
- 服务器 运行 是否在端口 3306 上?
- 是否禁用了 IPv4?
- 是否启用跳过网络?
- bind-address 是否已激活(使用另一个 IP?
我正在使用 PyMySQL to connect to a database running on localhost. I can access the database just fine using the username/password combiunation in both the command line and adminer 所以数据库似乎不是这里的问题。
我的代码如下。但是,当 使用 host="127.0.0.1"
选项时,我得到一个 OperationalError
和一个 Errno 111
。 使用相同的代码,但通过套接字连接 Mariadb 运行开就好了。
import pymysql.cursors
from pprint import pprint
# This causes an OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)")
# connection = pymysql.connect(
# host="127.0.0.1",
# port=3306,
# user="root",
# password="S3kr37",
# db="my_test",
# )
# This works.
connection = pymysql.connect(
user="root",
password="S3kr37",
db="my_test",
unix_socket="/var/lib/mysql/mysql.sock"
)
try:
with connection.cursor() as cursor:
sql = "select * from MySuperTable"
cursor.execute(sql)
results = cursor.fetchall()
pprint(results)
finally:
connection.close()
我做错了什么?
PS:请注意this question也有同样的问题,但提供的解决方案是套接字。 不够好: 我想知道为什么 我不能按照文档中的建议使用主机名。
客户端库返回错误代码 2003 (CR_CONN_HOST_ERROR),以防客户端无法与服务器建立 tcp 连接。
首先你应该检查,如果你可以通过 telnet 或 mysql 命令行客户端连接到你的服务器。 如果没有,检查服务器配置文件:
- 服务器 运行 是否在端口 3306 上?
- 是否禁用了 IPv4?
- 是否启用跳过网络?
- bind-address 是否已激活(使用另一个 IP?