命令不同步,您现在无法运行此命令

问题描述 投票:0回答:3

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

问题是执行python脚本时

db.py
mysql抛出错误:

_mysql_exceptions.ProgrammingError:(2014,“命令不同步;您现在无法运行此命令”)

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

表.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 个),它们看起来顺序正确。首先连接数据库,获取游标,最后执行查询创建表。这是错误的顺序吗?在连接到数据库之前进行查询似乎不合逻辑......

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

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

EDIT3:我发现如果我删除

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

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

python mysql synchronization mysql-python
3个回答
3
投票

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

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)

0
投票

我也遇到了同样的问题。

我已将 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


0
投票

我知道这个问题已经得到解答,但是我在使用 executemany

 方法运行具有多个参数的相同查询时遇到了相同的错误,并且无法在任何地方找到解决方案。因此,如果您正在阅读本文并遇到同样的问题,请尝试从 SQL 语句中删除分号。这为我解决了这个问题。

如文档中的示例所示,没有分号(10.5.8 MySQLCursor.executemany()方法):

data = [
  ('Jane', date(2005, 2, 12)),
  ('Joe', date(2006, 5, 23)),
  ('John', date(2010, 10, 3)),
]
stmt = "INSERT INTO employees (first_name, hire_date) VALUES (%s, %s)"
cursor.executemany(stmt, data)
© www.soinside.com 2019 - 2024. All rights reserved.