標籤:style blog http color io os ar for sp
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
123456 |
db MySQLdb.host port passwd db unix_socket |
(2)修改本地mysql server的UNIX Domain Socket
123456789101112 |
# The following options will be passed to all MySQL clients[client]#password = your_passwordport = 3306socket = /var/lib/mysql/mysql.sock # The MySQL server[mysqld]bind-address = 10.12.22.98port = 3306socket = /var/lib/mysql/mysql.sock# ... |
(3)修改本地mysql server支援遠端存取(具體見參考文獻(2)),採用普通socket進行串連
12345 |
db MySQLdb.host port passwd db |
-
4. 參考文獻
(1)Unix Domain Socket
(2)mysql支援遠端存取
python MySQLdb串連mysql失敗