python MySQLdb连接mysql失败
Traceback (most recent call last):
File "./test_db.py", line 12, in < module>
db='mysite')
File "build/bdist.linux-x86_64/egg/MySQLdb/__init__.py", line 81, in Connect
File "build/bdist.linux-x86_64/egg/MySQLdb/connections.py", line 187, in __init__
_mysql_exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)")
这里主要是因为我们连接mysql的时候,host用的是localhost, 实际用的是UNIX Domain Socket(具体见参考文献(1))来进行通信的。我们知道,UNIX Domain Socket的地址是一个socket类型的文件在文件系统中的路径,如果这个路径不存在的话,连接的时候就会失败。上面提示的错误原因是”Can’t connect to local MySQL server through socket ‘/var/lib/mysql/mysql.sock’ (2)”,从字面意思上来看,是说无法通过’/var/lib/mysql/mysql.sock’这个socket来连接本地的mysql sever,这时候问题基本就比较明显了,应该是mysql配置的本地连接的socket不是’/var/lib/mysql/mysql.sock’这个路径的原因。接下来我们来验证我们的想法,打开mysql的配置文件(/etc/my.cnf),我们看到如下的内容:
我们可以看到,本地mysql server配置的Unix Domain Socket是/tmp/mysql.sock,与上面python MySQLdb所用的不一样,这也印证了我们前面的猜想,找到了问题的原因。
3. 解决问题的方法
知道了问题所在,我们就可以对症下药了,下面提供几种可以解决问题的方案:
(1)在python MySQLdb连接的时候,指定所用的unix_socket
|
|
(2)修改本地mysql server的UNIX Domain Socket
|
|
(3)修改本地mysql server支持远程访问(具体见参考文献(2)),采用普通socket进行连接
|
|
4. 参考文献
(1)Unix Domain Socket
(2)mysql支持远程访问
转载于:https://my.oschina.net/netmouse/blog/335203
下一篇: Poi-2:个人记录使用过程的问题