PyMySQL使用本地主机与套接字不相干行为 [英] PyMySQL using localhost vs socket incoherant behaviour

查看:105
本文介绍了PyMySQL使用本地主机与套接字不相干行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 PyMySQL 连接到在本地主机上运行的数据库.我可以在命令行和管理员中使用用户名/密码组合来很好地访问数据库.似乎不是这里的探针.

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"选项时,我得到了OperationalErrorErrno 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.

推荐答案

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

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?

这篇关于PyMySQL使用本地主机与套接字不相干行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆