db = MySQLdb.connect(host='localhost',
port=3306,user='root',
passwd='root98',
db='mysite')
下面是运行的时候报的错误:
1
2
3
4
5
6
7
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)")
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),我们看到如下的内容:
1
2
3
4
5
6
7
8
9
10
11
12
# The following options will be passed to all MySQL clients
[client]
#password = your_password
port = 3306
socket = /tmp/mysql.sock
# The MySQL server
[mysqld]
bind-address = 10.12.22.98
port = 3306
socket = /tmp/mysql.sock
# ...
db = MySQLdb.connect(host='localhost',
port=3306,user='root',
passwd='root98',
db='mysite',
unix_socket='/tmp/mysql.sock')
(2)修改本地mysql server的UNIX Domain Socket
1
2
3
4
5
6
7
8
9
10
11
12
# The following options will be passed to all MySQL clients
[client]
#password = your_password
port = 3306
socket = /var/lib/mysql/mysql.sock
# The MySQL server
[mysqld]
bind-address = 10.12.22.98
port = 3306
socket = /var/lib/mysql/mysql.sock
# ...