Search code examples
pythonmysql

Python Mysql, "commands out of sync; you can't run this command now"


I have a MySQL stored procedure that is executed from Python (wrapped in Django). I get the error "commands out of sync; you can't run this command now" when I try to execute the second statement. I cannot commit the transaction at this point. This is only an issue when I call a procedure. What to do?

cursor.callproc('my_mysql_procedure', [some_id,]) 
result = cursor.fetchall()
for r in result:
    do something

cursor.execute("select * from some_table")
result = cursor.fetchall()

EDIT: I've been asked to post the MySQL procedure. I have made it super-simple and I still see the same problem

delimiter $$
create procedure my_mysql_procedure(p_page_id int)
    begin

        select 1
        from dual; 

    end$$
delimiter ;

Solution

  • Thanks to JoshuaBoshi for his answer, which solved the problem. After calling the procedure, I had to close the cursor and open it again before using it to execute another statement:

    cursor.close() 
    
    cursor = connection.cursor() 
    

    The cursor can be closed immediately after fetchall(). The result set still remains and can be looped through.