python下导入MySQLdb后的问题

司徒春运 发布于 2012/02/29 20:28
阅读 3K+
收藏 1

python使用MySQLdb库时,

>>> import MySQLdb
>>> db = MySQLdb.connect(user='root', db='mysql', passwd='111', host='localhost')

然后出错,错误信息:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/site-packages/MySQL_python-1.2.3-py2.6-linux-i686.egg/MySQLdb/__init__.py", line 81, in Connect
    return Connection(*args, **kwargs)
  File "/usr/lib/python2.6/site-packages/MySQL_python-1.2.3-py2.6-linux-i686.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 '/var/lib/mysql/mysql.sock' (2)")

/etc/my.cnf文件内容:

[mysqld]
datadir=/home/mysql/data
socket=/home/mysql/server/mysql.sock
user=mysql
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

[mysql]
socket=/home/mysql/server/mysql.sock

[client]
socket=/home/mysql/server/mysql.sock

请问怎么解决呢?

加载中
0
司徒春运
司徒春运

先多谢这个哥们的答案:http://www.cnblogs.com/trams/archive/2012/01/04/2311783.html

mysql.sock的路径没有设置好,通过unix_socket参数指定了sock文件的路径。

>>> db = MySQLdb.connect(user='***', db='***', passwd='***', host='localhost',unix_socket='/home/mysql/server/mysql.sock')
>>> cursor = db.cursor()
>>> cursor.execute('SELECT USER FROM user')
5L
>>> user = cursor.fetchall()
>>> print user
(('root',), ('ddmk',), ('qyli',), ('root',), ('root',))

0
mahone
mahone
直接命令行连连看?
0
whuiscool
whuiscool
我记得查看mysqldb 文档,参数的顺序是固定的: host_name,  user_name,  passwd,  db_name 
返回顶部
顶部