MySQLPython忽略了我的my.cnf文件,它从哪里获取信息?
当我尝试使用 MySQLPython(通过 SQLAlchemy)时,出现了这个错误:
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/MySQL_python-1.2.3c1-py2.6-macosx-10.6-x86_64.egg/MySQLdb/connections.py", line 188, in __init__
super(Connection, self).__init__(*args, **kwargs2)
sqlalchemy.exc.OperationalError: (OperationalError) (2002, "Can't connect to local MySQL server through socket '/opt/local/var/run/mysql5/mysqld.sock' (2)") None None
但是我机器上的其他 MySQL 客户端都能正常工作!
我的 my.cnf 文件里写的是:
[client]
port = 3306
socket = /tmp/mysql/mysql.sock
[safe_mysqld]
socket = /tmp/mysql/mysql.sock
[mysqld_safe]
socket = /tmp/mysql/mysql.sock
[mysqld]
socket = /tmp/mysql/mysql.sock
port = 3306
而且 mysql.sock 文件确实位于 /tmp/mysql 目录下。
我确认了 ~/.my.cnf 和 /var/lib/mysql/my.cnf 文件没有覆盖这个设置。mysql5 客户端程序等都能顺利连接,甚至在同一台机器上使用 jdbc/mysql 连接的 groovy/grails 安装也没有问题。
thrilllap-2:~ swirsky$ mysql5
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 6
Server version: 5.1.47 Source distribution
Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
This software comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to modify and redistribute it under the GPL v2 license
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| test |
+--------------------+
2 rows in set (0.00 sec)
mysql>
为什么 Python 的 MySQLdb 不能搞定这个问题?如果不看 my.cnf 文件,它会去哪里找呢?
4 个回答
2
顺便说一下:我通过把我的配置文件中的.sock文件位置改成MySQLdb想要的地方(/opt/local/var/run/mysql5/mysqld.sock)来“解决”这个问题,但我不喜欢这样做。
3
默认情况下,MysqlDBlib 不会读取 /etc/my.cnf 这个配置文件。如果你在 MySQLdb.connect 的调用中加上 read_default_group="client",它就会读取这个配置文件中的客户端部分。
4
你有没有试过在你的 connect()
调用中加上这个选项 read_default_file='~/.my.cnf'
,这样可以告诉Python的数据库驱动去读取你的配置文件?我觉得如果不加这个选项,它默认是会忽略这个文件的。