Python中的MySQLdb:“无法连接到'localhost'上的MySQL服务器" [英] MySQLdb in Python: "Can't connect to MySQL server on 'localhost'"

查看:265
本文介绍了Python中的MySQLdb:“无法连接到'localhost'上的MySQL服务器"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经为Python安装了MySQLdb,并且能够导入MySQLdb.现在,我尝试使用以下代码连接到本地计算机上的MySQL Community Server:

I have installed MySQLdb for Python and I am able to import MySQLdb. Now I try to connect to the MySQL Community Server on my local machine, using this code:

db=MySQLdb.connect(
    host="localhost",
    user="br_admin",
    passwd="blabla",
    db="br_brain"
)

此代码因以下错误而失败:

This code fails with this error:

Traceback (most recent call last):
  File "<pyshell#22>", line 5, in <module>
  db="brainse_brain"
File "C:\Python27\lib\site-packages\MySQLdb\__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 187, in __init__
super(Connection, self).__init__(*args, **kwargs2)
OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (10061)")

如何解决此错误?

推荐答案

请确保提供正确的主机和端口:

Make sure to provide the proper host and port:

'default': {
    'ENGINE': 'django.db.backends.mysql', 
    'NAME': 'yourdbname',                      
    'USER': 'root',                      
    'PASSWORD': 'your password',         
    'HOST': '127.0.0.1',                 
    'PORT': '3306',                      
},

这是我的Django应用程序的settings.py文件配置.

This is my settings.py file config for my django app.

与您相同,请使用主机"127.0.0.1"和端口"3306".

Same for you please take host "127.0.0.1" and port "3306".

这可能会解决您的问题. 对于python空闲,我已经测试过……

This might solve your problem. And for python idle I've tested like...

>>> import MySQLdb
>>> Con = MySQLdb.Connect(host="127.0.0.1", port=3306, user="yoruname", passwd="yourpwd", db="test")
>>> Cursor = Con.cursor()
>>> sql = "SELECT * FROM test.testing"
>>> Cursor.execute(sql)
2L

这篇关于Python中的MySQLdb:“无法连接到'localhost'上的MySQL服务器"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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