46

I'm trying to connect to MySQL on localhost using PyMySQL:

import pymysql
conn = pymysql.connect(db='base', user='root', passwd='pwd', host='localhost')

but (both on Python 2.7 and Python 3.2) I get the error:

socket.error: [Errno 111] Connection refused

pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (111)")

I'm sure mysqld is running because I can connect using mysql command or phpMyAdmin. Moreover, I can connect using MySQLdb on Python 2 with nearly the same code:

import MySQLdb
conn = MySQLdb.connect(db='base', user='root', passwd='pwd', host='localhost')

It seems that the problem is on PyMySQL side rather than MySQL but I have no idea how to solve it.

Community
  • 1
  • 1
O'Fermah
  • 565
  • 1
  • 6
  • 9

11 Answers11

76

Two guesses:

  1. Run mysqladmin variables | grep socket to get where the socket is located, and try setting up a connection like so:

    pymysql.connect(db='base', user='root', passwd='pwd', unix_socket="/tmp/mysql.sock")
    
  2. Run mysqladmin variables | grep port and verify that the port is 3306. If not, you can set the port manually like so:

    pymysql.connect(db='base', user='root', passwd='pwd', host='localhost', port=XXXX)
    
Ry-
  • 218,210
  • 55
  • 464
  • 476
Lucas Wiman
  • 10,021
  • 2
  • 37
  • 41
  • 3
    Sort of weird that it would be needed, though. I wonder if your `my.cnf` file isn't configured correctly. I'm guessing the port isn't configured right, and MySQLdb is smart enough to try to use the socket instead of TCP. (Some discussion [here](http://dev.mysql.com/doc/refman/5.5/en//connecting.html) where they talk about `--protocol`) – Lucas Wiman Jan 16 '13 at 06:39
  • 2
    I haven't actually got a `my.cnf` file - but PHP seems to be able to figure out that `localhost` should become that. I like using `.sock`s better, though :) – Ry- Jan 16 '13 at 06:40
  • I am really wonder ***why*** connecting via the socket works but not `localhost`. I mean, both adminer and mysql command line work fine with the credentials… – Sardathrion - against SE abuse Sep 04 '19 at 10:01
  • 1
    Been searching for days for an answer and your answer finally solved my problem here: https://stackoverflow.com/questions/60317075/pymysql-cant-connect-do-mysql-db-hangs-at-self-sock-recv-intob – J.E.C. Feb 20 '20 at 13:17
  • Your second guess led the way to the answer for me. The MySQL port was set up to the, non-default, 13306 so I had set the host to be '127.0.0.1:13306' which didn't work but setting the port via the 'port' parameter and leaving the host as '127.0.0.1' made it start to work. Thanks. – glaucon May 06 '23 at 05:07
13

Seems like changing localhost to 127.0.0.1 fixes the error, at least in my configuration. If it doesn't, I would look for errors in tcp sockets connection and, of course, post it as a bug in pymysql bugtrack.

ballade4op52
  • 2,142
  • 5
  • 27
  • 42
BrainStorm
  • 2,036
  • 1
  • 16
  • 23
  • 4
    This didn't fix it for me either. – gozzilli Sep 22 '12 at 22:11
  • I'm having similar trouble but using sqlalchemy --> pymysql --> mysql Can connect fine using commandline( mysql -h localhost ).... so it does seem to implicate pymysql – Steve G May 04 '18 at 18:57
8

I solved the issue by replacing localhost with 127.0.0.1 and changing the password to my MYSQL database password as shown below;

conn = pymysql.connect(
    host = '127.0.0.1',
    port = 3306,
    user = 'root',
    passwd = 'XXXXXXXXX',
    db = 'mysql'
)
dǝɥɔS ʇoıןןƎ
  • 1,674
  • 5
  • 19
  • 42
Byron Kiriibwa
  • 159
  • 1
  • 6
1

I met the same question and my solution is as follows:

  1. Run ssh -fN -L 3307:mysql_host:3306 ssh_user@ssh_host in my terminal.
  2. Then input your ssh password
  3. conn = pymysql.connect(db='base', user='root', passwd='pwd', host='localhost')

This error occurs because database does not support link directly.

Rex5
  • 771
  • 9
  • 23
wolfog
  • 731
  • 7
  • 10
1

I asked why socket worked but not TCP and the answer was that bind-address in /etc/my.cnf was not set correctly. This could be your problem too since the socket methods works just fine but the TCP one does not.

Sardathrion - against SE abuse
  • 17,269
  • 27
  • 101
  • 156
1

Those who are strugging to connect localhost MySQL from dockerised flask-sqlalchemy or using pymysql, pls look into this thread, very usefull How to connect locally hosted MySQL database with the docker container

Selvaraj S.
  • 124
  • 1
  • 5
0

This worked for me:

import pymysql

db = pymysql.connect(host="localhost",port=8889,user="root",passwd="root")
cursor=db.cursor()
cursor.execute("SHOW DATABASES")
results=cursor.fetchall()
for result in results:
    print (result)

if you want to find the port # go to mysql in terminal, and type:

SHOW VARIABLES WHERE Variable_name = 'hostname';
SHOW VARIABLES WHERE Variable_name = 'port';
0

I had this same problem on AWS - and turns out that my security group was blocking the connection. I temporarily opened up all connections and voila! It connected!

Do you have any type of FW or host-based FW that could be blocking the connection? I thought it was my code and all was fine. Also check the port you are connecting on.

S.B
  • 13,077
  • 10
  • 22
  • 49
0

If you are using Docker, you might need to use host.docker.internal instead of localhost.

cdutra
  • 587
  • 6
  • 15
0

I managed to solve my issue by using the port without any quotation like so:

port = 3306,
Rojin
  • 1,045
  • 9
  • 15
-1

You need to add the port to the connection as well. Try this and it works fine.

pymysql(Module Name).connect(host="localhost", user="root", passwd="root", port=8889, db="db_name")
Philipp Maurer
  • 2,480
  • 6
  • 18
  • 25
  • 5
    Welcome to SO! Before answering a question, always read the existing answers. This answer has already been provided. Instead of repeating the answer, vote up the existing answer. Some guidelines for writing good answers can be found here https://stackoverflow.com/help/how-to-answer – LightBender Dec 28 '17 at 14:57