Python中的MySQLdb:“无法连接到'localhost'上的MySQL服务器”

时间:2012-06-20 14:29:19

标签: mysql python-2.7

我已经为Python安装了MySQLdb,我可以导入MySQLdb。现在,我尝试使用以下代码连接到本地计算机上的MySQL社区服务器:

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

此代码因此错误而失败:

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)")

如何解决此错误?

7 个答案:

答案 0 :(得分:38)

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

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

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

同样请主持人“127.0.0.1”和端口“3306”。

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

>>> 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

答案 1 :(得分:6)

我也有同样的麻烦,我正在使用64位的Windows,而解决方案就是改变主机变量值。我已经设置了&#34; localhost&#34;当正确的值必须是&#34; 127.0.0.1&#34;。但是,当我在32位Windows上工作时。我可以设置&#34; localhost&#34;或&#34; 127.0.0.1&#34;在主机变量值中,无论如何,我的django项目运行完美。

答案 2 :(得分:3)

这样可以正常工作:

getCurrentLocation: function() {
      var currentLocation = this.removeHash(window.location.hash);

      return currentLocation;
   },

removeHash: function(hashValue) {
      if (hashValue == null || hashValue == undefined)
         return null;
      else if (hashValue == "")
         return "";
      else if (hashValue.length == 1 && hashValue.charAt(0) == "#")
         return "";
      else if (hashValue.length > 1 && hashValue.charAt(0) == "#")
         return hashValue.substring(1);
      else
         return hashValue;     
   },          

    db = MySQLdb.connect(host="127.0.0.1",user="db_username",passwd="db_password",db="db_name") 

答案 3 :(得分:1)

如果您使用的是Windows,则应将IP指定为&#34; 127.0.0.1&#34;,使用&#34; localhost&#34;会给你那个错误2003.在Ubuntu上我没有问题。

答案 4 :(得分:1)

在Windows 32中,如果将主机设置为127.0.01,则会出现关闭错误:

OperationalError: (2005, "Unknown MySQL server host '127.0.01' (0)")

但如果您将主机设置为127.0.0.1,则不会出现错误。

答案 5 :(得分:0)

1。转到MySQL工作台
2.在上面的任务栏上,单击服务器->,然后单击启动/关闭
3.在屏幕上,单击“启动服务器”,您将获得服务器启动和运行的日志

答案 6 :(得分:0)

 - DATABASES = {
       'default': {
           'ENGINE': 'django.db.backends.mysql',
           'NAME': 'dataflair',
           'USER':'root',
           'PASSWORD':'',
           'HOST':'127.0.0.1',
           'PORT':'3306',
           'OPTIONS':{
       'init_command':"SET sql_mode=STRICT_TRANS_TABLES" }
相关问题