pythonpython-db-api

How can I run multiple SQL statements in a query in python?


I'm implementing migrations for my program, and I need some way to run multiple statements in a query.

I have a dict of migrations:

MIGRATIONS = {
        "test": ("-- apply", "-- revert", "does nothing")
        }

(first tuple element is the "apply" query, second is the "revert" query, third is human-readable text for help pages)

I am currently using SQLite, but would like the option to switch to another DB in the future. As such, I can't use the Connection.executescript method, as that's "a nonstandard shortcut" for "a nonstandard convenience method".


Solution

  • Since you're implementing the migration, why don't you define a function that does it in terms of well-defined functions:

    def executemany(conn, statements: List[str]):
        with conn.cursor() as c:
            for statement in statements:
                c.execute(statement)
            conn.commit()
    

    Another option is to use a dedicated migration tool. I'm partial to goose.