Search code examples
pythonmysqlsynchronizationmysql-python

Commands out of sync you can't run this command now


I am trying to create some tables using mysqldb.

The issue is that when executing the python script db.py mysql throws the error:

_mysql_exceptions.ProgrammingError: (2014, "Commands out of sync; you can't run this command now")

db.py:

import MySQLdb
import MySQLdb.cursors

def init_db():
    db_conn = get_db_conn()
    cursor = db_conn.cursor()

    with open("tables.sql", 'r') as f:
        cursor.execute(f.read())

def get_db_conn():
    return MySQLdb.connect(
        host="localhost",
        user="root",
        passwd="secretcat",
        db="uptrender",
        cursorclass=MySQLdb.cursors.DictCursor
    )

init_db() 

tables.sql:

DROP TABLE IF EXISTS Test2;
DROP TABLE IF EXISTS Test;

CREATE TABLE Test (
    id INT NOT NULL
);

CREATE TABLE Test2 (
    id INT NOT NULL,
    FOREIGN KEY(id) REFERENCES Test(id)
);

According to the mysql docs this error is given when client functions are called in the wrong order. Looking at the ones i use (i only have 3 i think) they look to be in the correct order. First connecting to the database, getting the cursor and finally excecuting the query to create tables. Is this the wrong order? It would not seem logical to do the query before connecting to the database...

EDIT: I tried closing the connection after populating the database with tables but it makes no difference.

EDIT2: Furthermore i tried to drop the database completely and re-create it but mysql still throws the same error.

EDIT3: I found that if i remove the two DROP TABLES IF EXISTS tablename-statements in the top of tables.sql i do not get the error. But only the first table (test) seems to have been created (using SHOW TABLES; in the mysql command line client to verify this)! What the heck is going on there?

EDIT4: So i isolated the problem further, it had nothing to do with flask.


Solution

  • Okay, i figured out that i have to execute the statements one by one. I now do this:

    from flask import current_app, g
    
    import MySQLdb
    import MySQLdb.cursors
    import re
    
    def init_db():
        db_conn = get_db_conn()
        cursor = db_conn.cursor()
        f = current_app.open_resource("tables.sql")
        tables = f.read().decode('utf-8').split(';')
        f.close()
        for table in tables:
            table = re.sub('[\n\r]', '', table)
            if len(table) > 0:
                cursor.execute(table)