【问题标题】:Getting "Commands out of sync; you can't run this command now"获取“命令不同步;您现在无法运行此命令”
【发布时间】:2014-11-03 18:51:55
【问题描述】:

请原谅我,我对 python 还很陌生,而且我已经研究这个部分的逻辑很长一段时间了,但是,无论我尝试什么,它似乎总是在 print 语句中崩溃.基本上,我只是想知道 python 是否从 SQL 语句中获取了正确的值。我什至尝试过做一个 a,b,c = row.split(',') 然后是 print a 但它也会在打印时出错。

with con:
    cur.execute(query, (next, end,next,end))
    print (cur._last_executed)  # this prints the correct query.
    while True:
        result = cur.fetchmany()
        if len(result) ==0:
            break
        for row in result:
            myvalues = row.split(',')
            for value in myvalues:
                print value # this line is what the traceback says caused it.

错误输出:

Traceback (most recent call last):
  File "./export.py", line 55, in <module>
    print value
    File "/usr/local/lib/python2.7/dist-packages/MySQL_python-1.2.3-py2.7-linux-x86_64.egg/MySQLdb/connections.py", line 249, in __exit__
       self.rollback()
    _mysql_exceptions.ProgrammingError: (2014, "Commands out of sync; you can't run this command now")
    Exception _mysql_exceptions.ProgrammingError: (2014, "Commands out of sync; you can't run this command now") in <bound method SSCursor.__del__ of <MySQLdb.cursors.SSCursor object at 0x7fc0e0632f10>> ignored

【问题讨论】:

  • 我猜row 不是字符串,所以row.split 看起来不对...
  • 回溯清楚地表明当您调用self.rollback() 时发生了错误,您提供的代码中甚至都没有出现。此外,如果您不显示正在运行的命令,您希望我们如何调试您的命令如何不同步?
  • 请显示完整的回溯——从您提供的错误信息来看,print value 行似乎不是导致异常的原因。
  • 当您退出上下文管理器时实际上会发生错误 - 您通过执行 with con: 进入的那个。连接开始关闭,发出rollback,触发错误。不知道为什么会这样。您是否尝试在 with 块的末尾调用 cur.close()
  • 当您退出上下文管理器(with 块)时发生错误,而不是在 print 语句处。我的猜测是您的 SQL 命令与 Python DB API 的命令冲突。我特别猜测您的查询中可能有"COMMIT;",这可能会导致此错误(如this related question 所示)。

标签: python


【解决方案1】:

您的错误发生在您退出 with 块并调用 connection.__exit__ 时,而不是在 print 语句中。 当您查看这部分 MySQLdb 代码时,您会看到:

def __enter__(self): return self.cursor()

def __exit__(self, exc, value, tb):
    if exc:
        self.rollback()
    else:
        self.commit()

所以这立即告诉我们两件事:

  1. 有一个先前的异常被 rollback() 调用隐藏,它本身会导致异常
  2. 您的第一行应该是)with conn as cur:,因为cur 将被分配connection.__enter__() 的结果。

很难说你到底为什么会得到这个错误,因为我们不知道你的光标来自哪里。您应该按照上面的建议更改第一行,它可能会起作用。如果没有,请完全摆脱上下文管理器,您将能够看到原始异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-19
    • 2013-12-27
    • 2019-07-04
    • 2012-12-01
    • 1970-01-01
    • 2012-12-13
    • 1970-01-01
    相关资源
    最近更新 更多