Home > Database > Mysql Tutorial > body text

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

Linda Hamilton
Release: 2024-11-03 22:22:30
Original
852 people have browsed it

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)")
Copy after login

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
Copy after login

Network Connectivity

Confirm that the database host, typically localhost, is reachable from your computer. Run the following command:

ping localhost
Copy after login

Examine MySQL Socket Location

Execute the following command to determine the path to the MySQL socket:

mysqladmin variables | grep socket
Copy after login

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>
Copy after login

Verify MySQL Port

Use the command below to check the port used by your MySQL server:

mysqladmin variables | grep port
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template