Home > Database > Mysql Tutorial > body text

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

DDD
Release: 2024-11-04 11:51:12
Original
783 people have browsed it

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

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!