python MySQLdb连接mysql失败(转载)

最近了解了一下django,数据库选用了mysql, 在连接数据库的过程中,遇到一点小问题,在这里记录一下,希望能够对遇到同样的问题的朋友有所帮助,少走一些弯路。关于django,想在这里也额外说一句。django是很优秀的基于python的web开发框架,对于有python基础的后台程序员,如果有要做一些前台的需求,强烈推荐django。下面言归正传。

    • 1. 问题的现象

下面是连接数据库的代码,用的是python的MySQLdb模块:

1
2
3
4
5
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
# ...

我们可以看到,本地mysql server配置的Unix Domain Socket是/tmp/mysql.sock,与上面python MySQLdb所用的不一样,这也印证了我们前面的猜想,找到了问题的原因。

    • 3. 解决问题的方法

知道了问题所在,我们就可以对症下药了,下面提供几种可以解决问题的方案:
(1)在python MySQLdb连接的时候,指定所用的unix_socket

1
2
3
4
5
6
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
# ...

(3)修改本地mysql server支持远程访问(具体见参考文献(2)),采用普通socket进行连接

1
2
3
4
5
db = MySQLdb.connect(host='10.12.22.98',
                     port=3306,
                     user='root',
                     passwd='root98',
                     db='mysite')
    • 4. 参考文献

(1)Unix Domain Socket
(2)mysql支持远程访问

 

参考文章:http://www.wuzesheng.com/?p=2234

 

posted @ 2015-11-04 11:15  welkinok  Views(1497)  Comments(0Edit  收藏  举报