Python中使用MySQLdb連接數據庫時出現以下錯誤:
Traceback (most recent call last):
File "/home/monitor_user/serverMonitor.py", line 206, in <module>
ServerList = sqlQuery(getMngConn(), "select b.db_name, a.ip_inside, a.port from machine a inner join dbinfo b on b.machine_id = a.machine_id")
File "/home/monitor_user/serverMonitor.py", line 39, in getMngConn
return MySQLdb.connect(host='localhost', user='monitor_user', passwd='monitor.user', db='dbmanage')
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的sock文件已經調整到/tmp/mysql.sock,所以必須在mysqldb中指定sock的路徑(這個還是很不智能的,萬一我有很多mysql服務器,而每台服務器的sock路徑都有差異呢?)
return MySQLdb.connect(host='localhost', user='user', passwd='user', db='dbname', unix_socket='/tmp/mysql.sock' )
unix_socket參數指定了sock文件的路徑