Trouble Connecting to MySQL with PyMySQL on Localhost
When attempting to establish a connection to MySQL on localhost using PyMySQL:
<code class="python">import pymysql conn = pymysql.connect(db='base', user='root', passwd='pwd', host='localhost')</code>
One may encounter the following error:
socket.error: [Errno 111] Connection refused pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (111)")
This problem persists across both Python 2.7 and Python 3.2, despite MySQL running as confirmed by successful connections through mysql command or phpMyAdmin. Additionally, a nearly identical code snippet works using MySQLdb in Python 2.
Potential Solutions
Two possible explanations for this issue:
<code class="python">pymysql.connect(db='base', user='root', passwd='pwd', unix_socket="/tmp/mysql.sock")</code>
<code class="python">pymysql.connect(db='base', user='root', passwd='pwd', host='localhost', port=XXXX)</code>
The above is the detailed content of Why Can\'t I Connect to MySQL on Localhost with PyMySQL?. For more information, please follow other related articles on the PHP Chinese website!