PyMySQL 使用 localhost 与套接字不连贯的行为

2022-01-15 00:00:00 python mariadb mysql pymysql

我正在使用 PyMySQL 连接到在 localhost 上运行的数据库.我可以在命令行和 adminer 中使用用户名/密码组合访问数据库,所以数据库似乎不是这里的问题.

I am using 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 so the database does not appear to be the probem here.

我的代码如下.但是,当使用 host="127.0.0.1" 选项时,我得到一个 OperationalError 和一个 Errno 111. 使用相同的代码,但通过 Mariadb 运行的套接字连接是可以的.

My code is as follow. However, when using the host="127.0.0.1" options, I get an OperationalError and an Errno 111. Using the same code, but connecting via the socket Mariadb runs on is fine.

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:注意这个问题有同样的问题但是提供的解决方案是插座.这还不够好:我想知道为什么我不能按照文档的建议使用主机名.

PS: Note that this question has the same problem but the solution offered is the socket. That is no good enough: I want to know why I cannot use the hostname as the documentation suggests.

推荐答案

客户端库返回错误代码 2003 (CR_CONN_HOST_ERROR),以防客户端无法与服务器建立 tcp 连接.

Errorcode 2003 (CR_CONN_HOST_ERROR) is returned by the client library, in case the client wasn't able to establish a tcp connection to the server.

首先,您应该检查您是否可以通过 telnet 或 mysql 命令行客户端连接到您的服务器.如果不是,请检查服务器配置文件:

First you should check, if you can connect via telnet or mysql command line client to your server. If not, check the server configuration file:

  • 服务器是否在 3306 端口上运行?
  • 是否禁用了 IPv4?
  • 是否启用了跳过网络?
  • 绑定地址是否已激活(使用另一个 IP?

相关文章