Home >Database >Mysql Tutorial >Why Am I Getting a \'Connection Refused\' Error When Connecting to MySQL on Localhost with PyMySQL?

Why Am I Getting a \'Connection Refused\' Error When Connecting to MySQL on Localhost with PyMySQL?

Linda Hamilton
Linda HamiltonOriginal
2024-11-03 22:22:30906browse

Why Am I Getting a

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

  • Disable firewalls or antivirus software that may be blocking the database connection.
  • Ensure that the specified database user has access to the 'base' database.
  • Restart the MySQL service after making any configuration changes.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn