简体   繁体   English

MySQLdb.cursor.execute 不能运行多个查询

[英]MySQLdb.cursor.execute can't run multiple queries

We're trying to run SQL files containing multiple insert statements as a single query, but it seems rollback fails when any of the statements contain an error.我们试图将包含多个插入语句的 SQL 文件作为单个查询运行,但是当任何语句包含错误时, rollback似乎失败。

MySQLd configuration: MySQLd 配置:

sql_mode = STRICT_ALL_TABLES
default-storage-engine = innodb

Python code:蟒蛇代码:

from contextlib import closing
import MySQLdb
database_connection = MySQLdb.connect(host="127.0.0.1", user="root")
with closing(database_connection.cursor()) as cursor:
    database_connection.begin()
    cursor.execute('DROP DATABASE IF EXISTS db_name')
    cursor.execute('CREATE DATABASE db_name')
    cursor.execute('USE db_name')
    cursor.execute('CREATE TABLE table_name(first_field INTEGER)')
with closing(database_connection.cursor()) as cursor:
    try:
        database_connection.begin()
        cursor.execute('USE db_name')
        cursor.execute('INSERT INTO table_name VALUES (1)')
        cursor.execute('INSERT INTO table_name VALUES ("non-integer value")')
        database_connection.commit()
    except Exception as error:
        print("Exception thrown: {0}".format(error))
        database_connection.rollback()
        print("Rolled back")
with closing(database_connection.cursor()) as cursor:
    try:
        database_connection.begin()
        cursor.execute('USE db_name')
        cursor.execute('INSERT INTO table_name VALUES (1); INSERT INTO table_name VALUES ("non-integer value")')
        database_connection.commit()
    except:
        print("Exception thrown: {0}".format(error))
        database_connection.rollback()
        print("Rolled back")

Expected result: "Exception thrown" and "Rolled back" printed twice.预期结果:“抛出异常”和“回滚”打印两次。

Actual result with MySQL-python 1.2.4: MySQL-python 1.2.4 的实际结果:

Exception thrown: (1366, "Incorrect integer value: 'non-integer value' for column 'first_field' at row 1")
Rolled back
Exception thrown: (1366, "Incorrect integer value: 'non-integer value' for column 'first_field' at row 1")
Traceback (most recent call last):
  File "test.py", line 30, in <module>
    print("Rolled back")
  File ".../python-2.7/lib/python2.7/contextlib.py", line 154, in __exit__
    self.thing.close()
  File ".../virtualenv-python-2.7/lib/python2.7/site-packages/MySQLdb/cursors.py", line 100, in close
    while self.nextset(): pass
  File ".../virtualenv-python-2.7/lib/python2.7/site-packages/MySQLdb/cursors.py", line 132, in nextset
    nr = db.next_result()
_mysql_exceptions.OperationalError: (1366, "Incorrect integer value: 'non-integer value' for column 'first_field' at row 1")

What gives?什么给? Do we really have to parse the SQL to split up statements (with all the escape and quote handling that entails) to run them in multiple execute s?我们真的必须解析 SQL 来拆分语句(包括所有需要的转义和引号处理)以在多个execute运行它们吗?

Like all Python DB-API 2.0 implementations , the cursor.execute() method is designed take only one statement, because it makes guarantees about the state of the cursor afterward.像所有Python DB-API 2.0 实现一样cursor.execute()方法被设计为只使用一条语句,因为它保证了之后的游标状态。

Use the cursor.executemany() method instead.改用cursor.executemany()方法 Do note that, as per the DB-API 2.0 specification :请注意,根据 DB-API 2.0 规范

Use of this method for an operation which produces one or more result sets constitutes undefined behavior, and the implementation is permitted (but not required) to raise an exception when it detects that a result set has been created by an invocation of the operation.将此方法用于产生一个或多个结果集的操作构成未定义的行为,并且允许(但不是必需)实现在检测到已通过调用操作创建结果集时引发异常。

Using this for multiple INSERT statements should be just fine:将此用于多个INSERT语句应该没问题:

cursor.executemany('INSERT INTO table_name VALUES (%s)',
    [(1,), ("non-integer value",)]
)

If you need to execute a series of disparate statements like from a script, then for most cases you can just split the statements on ;如果您需要从脚本中执行一系列不同的语句,那么在大多数情况下,您只需将语句拆分为; and feed each statement to cursor.execute() separately.并将每个语句分别提供给cursor.execute()

I think you need to pass multi=True to execute when using multiple statements, see http://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html我认为您在使用多个语句时需要通过multi=Trueexecute ,请参阅http://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html

Update: This applies to the mysql.connector module, not MySQLdb used in this case.更新:这适用于mysql.connector模块,而不是在这种情况下使用的MySQLdb

显然是没有办法在做这个MySQLdb (又名。 MySQL-python ),因此,我们最后只是communicate荷兰国际集团的数据subprocess.Popen([mysql, ...], stdin=subprocess.PIPE)和检查returncode .

Tried the multi=True method, but ended up splitting the file by semi and looping through.尝试了multi=True方法,但最终通过半分割和循环来分割文件。 Obviously not going to work if you have escaped semis, but seemed like the best method for me.如果你已经逃脱了半决赛,显然不会起作用,但对我来说似乎是最好的方法。

with connection.cursor() as cursor:
    for statement in script.split(';'):
        if len(statement) > 0:
             cursor.execute(statement + ';')

Using the mysql program via Popen will definitely work, but if you want to just use an existing connection (and cursor), the sqlparse package has a split function that will split into statements.通过 Popen 使用mysql程序肯定会起作用,但是如果您只想使用现有的连接(和游标), sqlparse包有一个split函数,它将拆分为语句。 I'm not sure what the compatiblity is like, but I have a script that does:我不确定兼容性是什么样的,但我有一个脚本可以:

with open('file.sql', 'rb') as f:
    for statement in sqlparse.split(f.read()):
        if not statement:
            continue
        cur.execute(statement)

It's only ever fed DROP TABLE and CREATE TABLE statements, but works for me.它只提供 DROP TABLE 和 CREATE TABLE 语句,但对我有用。

https://pypi.python.org/pypi/sqlparse https://pypi.python.org/pypi/sqlparse

for _ in cursor.execute(query, multi=True): 
    pass

This works for me!这对我有用!

And according to the doc, this is the right thing to do, cursor.execute() returns an iterator and only when the contents in the iterator is consumed, will the commit be successful.根据文档,这是正确的做法, cursor.execute() 返回一个迭代器,只有当迭代器中的内容被消耗时,提交才会成功。

使用下面的行项目来执行语句:

for _ in cursor.execute(query, multi=True): pass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM