Home  >  Article  >  Database  >  Why Am I Getting \"Connection Refused\" Errors When Connecting to MySQL with PyMySQL?

Why Am I Getting \"Connection Refused\" Errors When Connecting to MySQL with PyMySQL?

Linda Hamilton
Linda HamiltonOriginal
2024-11-03 11:52:02547browse

Why Am I Getting

Troubleshooting "Connection Refused" Error when Connecting to MySQL with PyMySQL

When attempting to establish a connection to MySQL on localhost using PyMySQL, some users encounter the error "socket: [Errno 111] Connection refused." This can be frustrating, especially when MySQL is known to be running.

To understand the cause of this issue, let's examine two potential reasons:

  1. Incorrect socket path: PyMySQL may be attempting to connect to a different socket location than where MySQL is listening. To rectify this, run the command mysqladmin variables | grep socket to determine the socket's location. Then, set the unix_socket parameter when connecting, as follows:
<code class="python">pymysql.connect(db='base', user='root', passwd='pwd', unix_socket="/tmp/mysql.sock")</code>
  1. Mismatched port: MySQL may be listening on a port other than the default 3306. Verify this by running mysqladmin variables | grep port. If necessary, specify the correct port when connecting:
<code class="python">pymysql.connect(db='base', user='root', passwd='pwd', host='localhost', port=XXXX)</code>

By addressing one of these potential causes, you should be able to successfully establish a connection to MySQL on localhost using PyMySQL.

The above is the detailed content of Why Am I Getting \"Connection Refused\" Errors When Connecting to MySQL 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