Troubleshooting PyMySQL Connection Error when Connecting to MySQL on Localhost
When attempting to connect to a MySQL database on localhost using PyMySQL, you may encounter the error message:
socket.error: [Errno 111] Connection refused pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (111)")
To address this issue, consider the following troubleshooting steps:
Verify MySQL Service Status
Ensure that the MySQL service is running. You can check via the command prompt:
mysqladmin -u root -p status
Network Connectivity
Confirm that the database host, typically localhost, is reachable from your computer. Run the following command:
ping localhost
Examine MySQL Socket Location
Execute the following command to determine the path to the MySQL socket:
mysqladmin variables | grep socket
Set the unix_socket parameter in your PyMySQL connection string to the retrieved path. For example:
<code class="python">pymysql.connect(db='base', user='root', passwd='pwd', unix_socket="/tmp/mysql.sock")</code>
Verify MySQL Port
Use the command below to check the port used by your MySQL server:
mysqladmin variables | grep port
If the port is not the default 3306, set the port parameter in your PyMySQL connection string:
<code class="python">pymysql.connect(db='base', user='root', passwd='pwd', host='localhost', port=XXXX)</code>
Additional Troubleshooting Tips
The above is the detailed content of Why Am I Getting a \'Connection Refused\' Error When Connecting to MySQL on Localhost with PyMySQL?. For more information, please follow other related articles on the PHP Chinese website!