命令不同步你现在不能运行这个命令

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

我正在尝试使用 mysqldb 创建一些 table。

问题是在执行 python 脚本时 db.py mysql 抛出错误:

_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)
);

根据 mysql docs,当以错误的顺序调用客户端函数时会出现此错误。看看我使用的那些(我认为我只有 3 个)它们看起来顺序正确。首先连接到数据库,获取游标,最后执行查询以创建 tables。这是错误的顺序吗?在连接到数据库之前进行查询似乎不合逻辑...

编辑:我尝试在用 tables 填充数据库后关闭连接,但这没有任何区别。

EDIT2:此外,我尝试完全删除数据库并重新创建它,但 mysql 仍然抛出相同的错误。

EDIT3:我发现如果删除 tables.sql 顶部的两个 DROP TABLES IF EXISTS tablename 语句,我不会得到错误。但是似乎只创建了第一个 table(测试)(使用 mysql 命令行客户端中的 SHOW TABLES; 来验证这一点)!那里到底发生了什么?

EDIT4:所以我进一步隔离了问题,它与烧瓶无关。

好的,我发现我必须一条一条地执行这些语句。我现在这样做:

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)

我 运行 遇到了同样的问题。

我已将我的 SQL 插入语句转储到一个 .sql 文件中,以从没有其他方式相互通信的两个环境传输数据。

一个这样的文件如下所示:

USE `myDatabase`;
INSERT INTO `myTable` VALUES (
    some_value, some_value, some_value
);

我的 Python 代码按字面意思读取文件内容 运行:

print(f"Inserting data in to the `{database}` database...")
print("Running:\n"+ insert_query)
cursor.execute(insert_query)
cursor.close()
cnx.commit()

我最终遇到了与 OP 相同的错误。

我通过删除 .sql 文件中的 USE myDatabase 语句并改为 运行 来解决它:

print(f"Inserting data in to the `{database}` database...")
cursor.execute("USE myDatabase")
cursor.close()
print("Running:\n"+ insert_query)
cursor = cnx.cursor()
cursor.execute(insert_query)
cursor.close()
cnx.commit()

这就解决了问题。现在,这对于生产来说仍然不够好,因为我没有使用 SQL 语句 ,我读到它是不安全的。就我的目的而言,这已经足够了,但要记住这一点。对于构造这些插入语句的正确方法:https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-transaction.html