PyMySQL can't connect to MySQL on localhost

Two guesses:

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

Seems like changing localhost to 127.0.0.1 fixes the error, at least in my configuration. If it doesn't, I would look for errors in tcp sockets connection and, of course, post it as a bug in pymysql bugtrack.


I solved the issue by replacing localhost with 127.0.0.1 and changing the password to my MYSQL database password as shown below;

conn = pymysql.connect(
    host = '127.0.0.1',
    port = 3306,
    user = 'root',
    passwd = 'XXXXXXXXX',
    db = 'mysql'
)