无法使用Python的MySQLdb连接到localhost

时间:2011-01-11 20:37:16

标签: python mysql connect

我是新手,所以可能有错误的术语,但是当我运行以下脚本时:

import MySQLdb

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

我收到错误:

  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)")

该目录中没有名为mysql.sock的文件,但我不知道套接字是什么或如何使用MySQLdb模块为它指定正确的位置。

3 个答案:

答案 0 :(得分:38)

我设法通过将主机设置为“127.0.0.1”而不是“localhost”来解决此问题。

答案 1 :(得分:24)

如果你的mysql套接字没有放在/tmp/mysql.sock中,你可以用

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

编辑:对于macosx上的mamp,mysql套接字路径应该类似于/Applications/MAMP/tmp/mysql/mysql.sock

答案 2 :(得分:5)

您的mysql安装可能会将套接字放在其他位置。您可以在mysql配置文件中配置它。

您可能想查看此类似帖子:Installing mysql on leopard: "Can't connect to local MySQL server through socket"