python - 为什么现在还有 "commands out of sync; you can' t run this command”错误

标签 python mysql mysql-python

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

现在,我有几个客户端同时向服务器发送请求,服务器将查询 mysql 数据库,并将一些结果返回给客户端。我遇到错误。 2014,“命令不同步;您现在无法运行此命令”
我检查了 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 的正确方法,所以当我不共享连接时,问题就消失了。

MySQLdb User Guide 中的“threadSafety”下:

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.

关于python - 为什么现在还有 "commands out of sync; you can' t run this command”错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32755572/

相关文章:

python - 按行解析 HTML

python - Matplotlib 动画不在类内更新

mysql - sqlite GROUP BY 语句中的奇迹

mysql - 一个表中同一列上的两个外键

python - MySQL数据库更新到小数点

python - 如何使 Tesseract 更快

python psycopg2 - ProgrammingError : function crosstab(unknown, 未知)不存在

python - 在 Python 中无需重启应用程序即可检索 MySQL 数据库的新行

mysql - 如何在 bash 中捕获 mysql 错误

database - 插入列表时python2.7 MySQLdb语法错误