Python – MySQLdb connection problems

connectionmysqlpython

I'm having trouble with the MySQLdb module.

db = MySQLdb.connect(
    host = 'localhost', 
    user = 'root', 
    passwd = '', 
    db = 'testdb', 
    port = 3000)

(I'm using a custom port)

the error I get is:

Error 2002: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

Which doesn't make much sense since that's the default connection set in my.conf.. it's as though it's ignoring the connection info I give..

The mysql server is definitely there:

[root@baster ~]# mysql -uroot -p -P3000
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 19
Server version: 5.0.77 Source distribution

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql> use testdb;
Database changed
mysql> 

I tried directly from the python prompt:

>>> db = MySQLdb.connect(user='root', passwd='', port=3000, host='localhost', db='pyneoform')
Traceback (most recent call last):
File "", line 1, in 
File "/usr/lib64/python2.5/site-packages/MySQLdb/__init__.py", line 74, in Connect
return Connection(*args, **kwargs)
File "/usr/lib64/python2.5/site-packages/MySQLdb/connections.py", line 169, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)")
>>>

I'm confused… 🙁

Best Solution

Changing localhost to 127.0.0.1 solved my problem using MySQLdb:

db = MySQLdb.connect(
    host = '127.0.0.1', 
    user = 'root', 
    passwd = '', 
    db = 'testdb', 
    port = 3000)

Using 127.0.0.1 forces the client to use TCP/IP, so that the server listening to the TCP port can pickle it up. If host is specified as localhost, a Unix socket or pipe will be used.

Related Question