出现“命令不同步;现在无法运行此命令”错误

0 投票
1 回答
3111 浏览
提问于 2025-05-01 09:14

请原谅我,我对Python还比较陌生,最近一直在研究这段代码的逻辑。不过,不管我怎么尝试,程序在打印输出的那一行总是崩溃。其实,我只是想确认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
暂无标签

1 个回答

1

你的错误发生在你退出 with 块的时候,这时会调用 connection.__exit__,而不是在打印语句那一行。

看看 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__() 的结果。

很难说你为什么会得到这个错误,因为我们不知道你的游标是从哪里来的。你应该按照上面的建议修改你的第一行,这样可能就能解决问题。如果还是不行,那就完全去掉上下文管理器,这样你就能看到原始的异常信息了。

撰写回答