命令不同步现在不能运行此命令

kx1ctssn  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(433)

我正在尝试使用mysqldb创建一些表。
问题是在执行python脚本时 db.py mysql抛出错误:
_mysql\u exceptions.programmingerror:(2014),“命令不同步;现在不能运行此命令“)
数据库类型:

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()

表.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文档,当以错误的顺序调用客户机函数时,就会出现这个错误。看看我用的那些(我想只有3个),它们看起来顺序正确。首先连接到数据库,获取游标,最后执行查询以创建表。这是错误的顺序吗?在连接到数据库之前执行查询似乎不符合逻辑。。。
edit:在用表填充数据库之后,我尝试关闭连接,但没有任何区别。
edit2:此外,我试图完全删除数据库并重新创建它,但是mysql仍然抛出相同的错误。
edit3:我发现如果我去掉这两个 DROP TABLES IF EXISTS tablename -最上面的语句 tables.sql 我不明白这个错误。但是似乎只创建了第一个表(test)(使用 SHOW TABLES; 在mysql命令行客户端进行验证)!那到底是怎么回事?
edit4:所以我进一步隔离了这个问题,它与 flask 无关。

jecbmhm3

jecbmhm31#

好吧,我想我必须一个接一个地执行这些语句。我现在这样做:

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)

相关问题