4

As part of a larger debugging effort, I've run into the following bug using 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

The relevant pieces of my code are as follows:

connection = mysqldb.connect('localhost', 'root', 'password', 'db')
cursor = connection.cursor()
file = open(filename, 'r')
sql = s = " ".join(file.readlines)
cursor.execute(sql)
cursor.close()
...

The error is thrown on the cursor.close() line before I get into anything else, which makes no sense to me... Anybody know what I'm doing wrong? There's only a single thread used in all the code.

1 Answer 1

7

In case anybody else runs into this error, my problem was the the file I was reading had multiple sql statements in it (separated by ;s). The cursor.execute() could only handle one of them at a time, or something, and was freaking out when I tried to close it.

Solution:

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()
Sign up to request clarification or add additional context in comments.

1 Comment

Doing it one statement at a time fixed my problem, but I don't understand why. Sometimes I'm able to execute multiple statements at a time, and sometimes I'm not. Is there a way to execute multiple statements together without running into this error?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.