作为更大调试工作的一部分,我使用mysqldb遇到了以下错误:
File "x.py" line x, in method
cursor.close()
File "y.py" line 100, in close
while self.nextset(): pass
File "z.py" line 137, in nextset
self._waring_check()
...
Exception _mysql_exceptions.ProgrammingError: (2014, "Commands out of sync; you can't run this command now") in <bound method Cursor.__del__ of <MySQLdb.cursor.Cursor object at 0x000002373198>> ignored
我的代码的相关部分如下:
connection = mysqldb.connect('localhost', 'root', 'password', 'db')
cursor = connection.cursor()
file = open(filename, 'r')
sql = s = " ".join(file.readlines)
cursor.execute(sql)
cursor.close()
...
在我进入其他任何东西之前,会在cursor.close()行上抛出错误,这对我来说没有任何意义......有人知道我做错了什么吗?在所有代码中只使用了一个线程。
答案 0 :(得分:7)
如果有其他人遇到此错误,我的问题是我正在阅读的文件中有多个sql语句(由; s分隔)。 cursor.execute()一次只能处理其中一个,或者什么东西,当我试图关闭它时它就吓坏了。
解决方案:
connection = mysqldb.connect('localhost', 'root', 'password', 'db')
file = open(filename, 'r')
sql_statements = " ".join(file.readlines())
for sql in sql_statements.split(";"): //given file, may need ";\n"
cursor = connection.cursor()
cursor.execute(sql)
cursor.close()