MySQLdb in Python: “Can't connect to MySQL server on 'localhost'”

后端 未结 6 950
没有蜡笔的小新
没有蜡笔的小新 2020-12-08 10:15

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:



        
相关标签:
6条回答
  • 2020-12-08 10:57

    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',                      
    },
    

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

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

    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
    
    0 讨论(0)
  • 2020-12-08 11:01

    If you are using windows you should specify the IP to "127.0.0.1", using "localhost" will give you that error 2003. On Ubuntu I had no problem.

    0 讨论(0)
  • 2020-12-08 11:01

    1.Go to MySQL workbench
    2.On the task bar above, click on server->and then click on Startup/Shutdown
    3.On the screen, click on Start the server and you will get logs of server starting and running

    0 讨论(0)
  • 2020-12-08 11:04

    This will work fine :

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

    or

       db=  MySQLdb.connect("127.0.0.1","db_username","db_password","db_name")
    
    0 讨论(0)
  • 2020-12-08 11:11

    I had the same trouble too, I'm working on a Windows of 64 bits, and the solution just was changing the host variable value. I had set "localhost" when the correct value have to be "127.0.0.1". However, when I'm working on Windows of 32 bits. I can set "localhost" or "127.0.0.1" in the host variable value and no matter, my django's project runs perfectly.

    0 讨论(0)
  • 2020-12-08 11:13

    In Windows 32, if you set host as 127.0.01 it gives the down error:

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

    But if you set host as 127.0.0.1 then you get no error.

    0 讨论(0)
提交回复
热议问题