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()


你可能感兴趣的:(Python,mysql,异常)