Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyMySQL can't connect to MySQL on localhost

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.

like image 556
O'Fermah Avatar asked Jul 30 '11 18:07

O'Fermah


People also ask

Can't connect to local MySQL server on localhost?

normally means that there is no MySQL server running on the system or that you are using an incorrect Unix socket file name or TCP/IP port number when trying to connect to the server. You should also check that the TCP/IP port you are using has not been blocked by a firewall or port blocking service.

How do I access MySQL server on localhost?

Enter 127.0. 0.1 for the host. The default username for a new MySQL installation is root, with a blank password. You can leave the port field blank unless your server uses a different port than 3306.

What is difference between PyMySQL and MySQL connector?

PyMySQL is a pure-Python MySQL client library, based on PEP 249. Most public APIs are compatible with mysqlclient and MySQLdb. PyMySQL works with MySQL 5.5+ and MariaDB 5.5+. MySQL is a leading open source database management system.

Can't connect to MySQL server on timed out?

A Connection Timed Out error occurs when the database's firewall won't allow you to connect to the database from your local machine or resource. If you are getting this error, check that you have added the machine or resource you are connecting from to the database's list of trusted sources.


2 Answers

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) 
like image 143
RecursivelyIronic Avatar answered Sep 22 '22 03:09

RecursivelyIronic


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.

like image 31
BrainStorm Avatar answered Sep 24 '22 03:09

BrainStorm