"""对比逐条 INSERT 与 executemany 的语句数。""" from __future__ import annotations from sqlalchemy import ( Column, Engine, Integer, MetaData, String, Table, create_engine, event, func, insert, select, ) ROWS = 200 def build() -> tuple[Engine, Table]: engine = create_engine("sqlite:///:memory:") metadata = MetaData() items = Table( "items", metadata, Column("id", Integer, primary_key=True), Column("name", String, nullable=False), ) metadata.create_all(engine) return engine, items def rows() -> list[dict[str, object]]: return [{"name": f"item-{index}"} for index in range(ROWS)] def count_statements(engine: Engine, table: Table, bulk: bool) -> tuple[int, int]: statements: list[str] = [] def before_cursor_execute(*args: object) -> None: statements.append("sql") event.listen(engine, "before_cursor_execute", before_cursor_execute) try: with engine.begin() as connection: if bulk: connection.execute(insert(table), rows()) else: for row in rows(): connection.execute(insert(table).values(**row)) finally: event.remove(engine, "before_cursor_execute", before_cursor_execute) with engine.connect() as connection: count = connection.execute(select(func.count()).select_from(table)).scalar_one() return len(statements), int(count) def main() -> None: engine, table = build() loop_statements, _ = count_statements(engine, table, bulk=False) engine, table = build() bulk_statements, count = count_statements(engine, table, bulk=True) print(f"loop_statements: {loop_statements}") print(f"bulk_statements: {bulk_statements}") print(f"rows: {count}") if __name__ == "__main__": main()