为什么还有 "commands out of sync; you can't run this command now" 错误

Why still has "commands out of sync; you can't run this command now" error

我正在使用 Python mysqldb 库连接 mysql 数据库。我有一个带有 4 个工作进程的 Web 服务器,它有 1 个连接和 1 个游标 到 mysql 数据库。所以每个工作进程都会使用它的 connection/cursor 来执行 sql 语句。

现在,我有多个客户端同时向服务器发送请求,服务器将查询 mysql 数据库,并将 return 一些结果发送给客户端。我遇到错误。 2014, "Commands out of sync; you can't run this command now"
我检查了 sql,它就像 SELECT a, b, c from table WHERE a = 1 一样简单。没有分号或存储过程,我也按照 Python, "commands out of sync; you can't run this command now" 的建议尝试下面的代码。但它仍然是同样的错误。

self.cursor.execute(sql, data)
self.conn.commit()
result = result + self.cursor.fetchall()
self.cursor.close()
self.cursor = self.conn.cursor() 

最后,我解决了这个问题。我的应用程序有多线程使用相同的连接,这似乎不是访问 mysql 的正确方法,所以当我不共享连接时,问题就消失了。

在'threadSafety'下MySQLdb User Guide:

The MySQL protocol can not handle multiple threads using the same connection at once. Some earlier versions of MySQLdb utilized locking to achieve a threadsafety of 2. While this is not terribly hard to accomplish using the standard Cursor class (which uses mysql_store_result()), it is complicated by SSCursor (which uses mysql_use_result(); with the latter you must ensure all the rows have been read before another query can be executed. It is further complicated by the addition of transactions, since transactions start when a cursor execute a query, but end when COMMIT or ROLLBACK is executed by the Connection object. Two threads simply cannot share a connection while a transaction is in progress, in addition to not being able to share it during query execution. This excessively complicated the code to the point where it just isn't worth it.

The general upshot of this is: Don't share connections between threads. It's really not worth your effort or mine, and in the end, will probably hurt performance, since the MySQL server runs a separate thread for each connection. You can certainly do things like cache connections in a pool, and give those connections to one thread at a time. If you let two threads use a connection simultaneously, the MySQL client library will probably upchuck and die. You have been warned.