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

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

DDD
DDDOriginal
2024-11-04 11:51:12824browse

Why Can't I Connect to MySQL on Localhost with PyMySQL?

Trouble Connecting to MySQL with PyMySQL on Localhost

When attempting to establish a connection to MySQL on localhost using PyMySQL:

<code class="python">import pymysql
conn = pymysql.connect(db='base', user='root', passwd='pwd', host='localhost')</code>

One may encounter the following error:

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

This problem persists across both Python 2.7 and Python 3.2, despite MySQL running as confirmed by successful connections through mysql command or phpMyAdmin. Additionally, a nearly identical code snippet works using MySQLdb in Python 2.

Potential Solutions

Two possible explanations for this issue:

  1. Socket Location: Use mysqladmin variables | grep socket to identify the socket location and connect using:
<code class="python">pymysql.connect(db='base', user='root', passwd='pwd', unix_socket="/tmp/mysql.sock")</code>
  1. Port Assignment: Check that the port is set to 3306 using mysqladmin variables | grep port. If it differs, manually specify the port in the connection:
<code class="python">pymysql.connect(db='base', user='root', passwd='pwd', host='localhost', port=XXXX)</code>

The above is the detailed content of Why Can\'t I Connect 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