开发者社区> 问答> 正文

python下导入MySQLdb后的问题 python使用MySQLdb库时,? 400 报错

python下导入MySQLdb后的问题 python使用MySQLdb库时,? 400 报错

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

请问怎么解决呢?

展开
收起
爱吃鱼的程序员 2020-05-30 21:37:14 623 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    先多谢这个哥们的答案: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',))

    ######直接命令行连连看?######我记得查看mysqldb 文档,参数的顺序是固定的: host_name,  user_name,  passwd,  db_name 
    2020-05-30 21:37:15
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载