Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

python - PyMySQL can't connect to MySQL on localhost

I'm trying to connect to MySQL on localhost using PyMySQL:

import pymysql
conn = pymysql.connect(db='base', user='root', passwd='pwd', host='localhost')

but (both on Python 2.7 and Python 3.2) I get the error:

socket.error: [Errno 111] Connection refused

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

I'm sure mysqld is running because I can connect using mysql 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')

It seems that the problem is on PyMySQL side rather than MySQL but I have no idea how to solve it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...