PyMySQL 无法连接到本地主机上的 MySQL

2021-11-20 00:00:00 python mysql mysql-error-2003

我正在尝试使用 PyMySQL 连接到本地主机上的 MySQL:

I'm trying to connect to MySQL on localhost using PyMySQL:

import pymysql
conn = pymysql.connect(db='base', user='root', passwd='pwd', host='localhost')

但是(在 Python 2.7 和 Python 3.2 上)我收到错误:

but (both on Python 2.7 and Python 3.2) I get the error:

socket.error: [Errno 111] 连接被拒绝

socket.error: [Errno 111] Connection refused

pymysql.err.OperationalError: (2003, 无法连接到 'localhost' (111) 上的 MySQL 服务器")

pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (111)")

我确定 mysqld 正在运行,因为我可以使用 mysql 命令或 phpMyAdmin 进行连接.此外,我可以使用几乎相同的代码在 Python 2 上使用 MySQLdb 进行连接:

I'm sure mysqld is running because I can connect using mysql command or phpMyAdmin. Moreover, I can connect using MySQLdb on Python 2 with nearly the same code:

import MySQLdb
conn = MySQLdb.connect(db='base', user='root', passwd='pwd', host='localhost')

问题似乎出在 PyMySQL 端而不是 MySQL 上,但我不知道如何解决.

It seems that the problem is on PyMySQL side rather than MySQL but I have no idea how to solve it.

推荐答案

两个猜测:

  1. 运行 mysqladmin 变量 |grep socket 获取套接字所在的位置,然后尝试像这样建立连接:

  1. Run mysqladmin variables | grep socket to get where the socket is located, and try setting up a connection like so:

pymysql.connect(db='base', user='root', passwd='pwd', unix_socket="/tmp/mysql.sock")

  • 运行 mysqladmin 变量 |grep 端口 并验证端口是 3306.如果不是,您可以像这样手动设置端口:

  • Run mysqladmin variables | grep port and verify that the port is 3306. If not, you can set the port manually like so:

    pymysql.connect(db='base', user='root', passwd='pwd', host='localhost', port=XXXX)
    

  • 相关文章