python 连接 mysql 错误

错误一:

File "/usr/lib/pymodules/python2.6/MySQLdb/__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "/usr/lib/pymodules/python2.6/MySQLdb/connections.py", line 170, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on 'xxx.xxx.xxx.xxx' (111)")

 

解决方法:

1、编辑my.cnf,默认为/etc/mydql/my.cnf,注释掉bind-address = 127.0.0.1或者修改为0.0.0.0;

# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
# bind-address           = 127.0.0.1

2、重启mysql:

sudo /etc/init.d/mysql restart 

 

错误二:

File "/usr/lib/pymodules/python2.6/MySQLdb/__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "/usr/lib/pymodules/python2.6/MySQLdb/connections.py", line 170, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (1130, "Host 'xxx.xxx.xxx.xxx' is not allowed to connect to this MySQL server")

 

解决方法:

mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'root' WITH GRANT OPTION;

该语句意思为:允许所有用root用户并且输入root密码的主机登入该mysql Server。

用户名和密码替换为需要的,如果将'%'换成相应主机名那么只有该主机可以登陆。

 

错误三:

(1040, 'Too many connections')
The reason is:  'NoneType' object has no attribute 'cursor'

网络爬虫改为多线程后,连接数据库出现以上错误。

 

解决方法一:

编辑my.cnf,默认为/etc/mydql/my.cnf,修改max_connections的值为10000,默认为100,实际MySQL服务器允许的最大连接数16384。

解决方法二:

使用数据库连接池。

解决方法三:

之前的程序结构为抓取到一条数据即产生一条sql语句即插入一条数据,修改程序结构为将各进程线程产生的sql语句put进Queue,用一个单独的进程不断get出sql插入数据库。

 

参考:

http://stackoverflow.com/questions/8960965/python-and-mysqldb-connection-to-another-server-on-the-network

 

原文:http://www.cnblogs.com/congbo/archive/2012/08/27/2658039.html

posted @ 2012-08-27 14:24  congbo  阅读(6088)  评论(0编辑  收藏  举报