MySQLdb.cursor.execute can't run multiple queries

前端 未结 7 1337
暗喜
暗喜 2020-12-06 05:11

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.

7条回答
  •  独厮守ぢ
    2020-12-06 05:37

    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. 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.

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

提交回复
热议问题