MySQL Connection not available

今天踩到了一个坑:用Python3.3读写mysql数据库的时候,老是报MySQL Connection not available的异常,百思不得其解!

最后搞了一个早上,终于在大海里面捞到了一根针:http://bugs.mysql.com/bug.php?id=67649


If you open an unbuffered cursor and you do not read the WHOLE result set before closing the cursor, the next query will fail with

  File "/usr/lib/python3.2/site-packages/mysql/connector/connection.py", line 1075, in cursor
    raise errors.OperationalError("MySQL Connection not available.")
mysql.connector.errors.OperationalError: MySQL Connection not available.

and all subsequent database calls will fail too.


总结下来就是说,如果你打开了一个cursor,但是没有把里面的结果集都read一遍就把它close掉了,以后就悲剧了。

后来在mysql官网的文档(http://dev.mysql.com/doc/refman/5.7/en/connector-python-api-mysqlcursor.html)上面寻寻觅觅,发现这么一句话:

You must fetch all rows before being able to execute new queries using the same connection.

哎!不看文档害死人啊!!但是我看过好几遍也没注意到这句话死得不冤啊!!!


====================2013-11-13 补充====================

看了一下Python文档里面关于sqlite3的部分,貌似并没有指出一定要把cursor里面的内容都读完才能关掉。所以测试了一下Python3里自带的sqlite3的情况,得出的结论确实是cursor里面的内容没有全部read一遍关掉,并不会有任何异常。

测试代码如下:

import sqlite3

conn = sqlite3.connect('data.db');
cursor = conn.cursor()
cursor.execute("select * from TSite")
print(cursor.fetchone())
print(cursor.fetchone())
cursor.close()
cursor = conn.cursor()
cursor.execute("select * from TSite")
print(cursor.fetchone())
print(cursor.fetchone())
cursor.close()


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值