本文介绍了PyMySQL无法连接到本地主机上的MySQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用PyMySQL连接到localhost上的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:

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

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

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

I'm sure mysqld is running because I can connect using 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 variables | 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 variables | grep port并验证端口是否为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)
    

  • 这篇关于PyMySQL无法连接到本地主机上的MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    07-16 05:55