Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't connect to localhost using Python's MySQLdb

I'm new to this so probably have the wrong terminology but when I run the following script:

import MySQLdb

conn = MySQLdb.connect (host = 'localhost',
   user = 'erin',
   passwd = 'erin',
          db = 'sec')

I get the error:

  File "/Library/Python/2.6/site-packages/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg/MySQLdb/__init__.py", line 81, in Connect
    return Connection(*args, **kwargs)
  File "/Library/Python/2.6/site-packages/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg/MySQLdb/connections.py", line 187, in __init__
    super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)")

There is no file called mysql.sock in that directory but I don't know what a socket is or how to specify the correct location for it using the MySQLdb module.

like image 252
erin Avatar asked Jan 11 '11 20:01

erin


People also ask

How do you fix MySQL can't connect to localhost?

Go to start- MySQL Installer-community and run again the installer as a re-configuration(you will be asked so). Once asked if you want make MySQL instance to run as a Windows service, check the box. In case would do not work, try unistalling and installing again, and check the box to run MySQL as Windows service.

What is MySQLdb in Python?

MySQLdb is an interface for connecting to a MySQL database server from Python. It implements the Python Database API v2. 0 and is built on top of the MySQL C API. Packages to Install. mysql-connector-python mysql-python.

Can't connect to MySQL server on localhost in flask?

Simply, write conn. close() and cursor. close(). It should resolve your problem.


2 Answers

I've managed to solve this by setting my host to "127.0.0.1" rather than "localhost".

like image 96
k0nG Avatar answered Oct 11 '22 17:10

k0nG


if your mysql socket is not placed in /tmp/mysql.sock, you can specify it with

conn = MySQLdb.connect (unix_socket = 'path_to_your_socket', host = 'localhost', user = 'erin', passwd = 'erin', db = 'sec')

edit: for mamp on macosx the mysql socket path should be something like /Applications/MAMP/tmp/mysql/mysql.sock

like image 22
roman Avatar answered Oct 11 '22 19:10

roman