Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysqldb cursor.close() throws ProgrammingError: (2014, "commands out of sync...") when executing sql read from file

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.

like image 903
user2048643 Avatar asked Mar 21 '23 14:03

user2048643


1 Answers

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()
like image 50
user2048643 Avatar answered Apr 06 '23 16:04

user2048643