[Python] SQLAlchemy mssql: Drop/Create Table on the Fly

Discussão em 'Python' iniciado por Stack, Março 27, 2025.

  1. Stack

    Stack Membro Participativo

    I've created a SQLAlchemy (2.0.39), Python (3.10.11) definition on the fly:

    dynamic_class = type(table_name, (Base,), attributes)


    This is working, now I want to drop any existing table and recreate it using the current definition (and where the problems kick in)

    log.info(f"Dropping Table: mygrc.{table_name}")
    dynamic_class__table__.drop(dbEngine, checkfirst=True)

    log.info(f"Creating Table: mygrc.{table_name}")
    Base.metadata.create_all(dbEngine, tables=[dynamic_class.__table__])


    Both the drop and create statements give me errors:


    No results. Previous SQL was not a query.
    ​

    If I try to pass the query direct to execute, it doesn't error but it doesn't execute the command either (even with a commit)

    with dbEngine.connect() as connection:
    create_table_statement = str(dynamic_class.__table__.compile(dbEngine))
    connection.execute(text(create_table_statement))


    create_table_statement gives me a valid create statement.

    Any ideas?

    Continue reading...

Compartilhe esta Página