Home >Database >Mysql Tutorial >Why Can\'t PyMySQL Connect to MySQL on Localhost?

Why Can\'t PyMySQL Connect to MySQL on Localhost?

Linda Hamilton
Linda HamiltonOriginal
2024-11-06 03:22:02349browse

Why Can't PyMySQL Connect to MySQL on Localhost?

pymysql Cannot Connect to MySQL on Localhost

When attempting to establish a connection to MySQL on localhost using PyMySQL, an error typically arises:

socket.error: [Errno 111] Connection refused
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (111)")

Despite the confirmation that MySQL is running, the connection fails using PyMySQL, while MySQLdb allows for a successful connection on Python 2.

Potential Solutions:

  1. Socket Location: Determine the socket's location by executing mysqladmin variables | grep socket. Provide the socket path during the connection setup:
pymysql.connect(db='base', user='root', passwd='pwd', unix_socket="/tmp/mysql.sock")
  1. Port Verification: Check that the MySQL port is 3306 using mysqladmin variables | grep port. If it differs, specify the port manually:
pymysql.connect(db='base', user='root', passwd='pwd', host='localhost', port=XXXX)

One of these approaches should resolve the connection issue between PyMySQL and MySQL on localhost.

The above is the detailed content of Why Can\'t PyMySQL Connect to MySQL on Localhost?. 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