How to delete a table in SQLAlchemy?

前端 未结 4 910
无人共我
无人共我 2020-12-02 15:23

I want to delete a table using SQLAlchemy.

Since I am testing over and over again, I want to delete the table my_users so that I can start from scratch

相关标签:
4条回答
  • 2020-12-02 15:47

    Alternative to calling cls.__table__.drop(your_engine), you can try this:

    Base.metadata.drop_all(bind=your_engine, tables=[User.__table__])
    

    This method as well as the create_all() method accept an optional argument tables, which takes an iterator of sqlalchemy.sql.schema.Table instances.

    You can control which tables are to be created or dropped in this way.

    0 讨论(0)
  • 2020-12-02 15:53

    For the special case when you don't have access to the table class and just need to delete the table by table name then use this code

    import logging
    from sqlalchemy import MetaData
    from sqlalchemy import create_engine
    from sqlalchemy.engine.url import URL
    from sqlalchemy.ext.declarative import declarative_base
    
    DATABASE = {
       'drivername': 'sqlite',
       # 'host': 'localhost',
       # 'port': '5432',
       # 'username': 'YOUR_USERNAME',
       # 'password': 'YOUR_PASSWORD',
       'database': '/path/to/your_db.sqlite'
    }
    
    def drop_table(table_name):
       engine = create_engine(URL(**DATABASE))
       base = declarative_base()
       metadata = MetaData(engine, reflect=True)
       table = metadata.tables.get(table_name)
       if table is not None:
           logging.info(f'Deleting {table_name} table')
           base.metadata.drop_all(engine, [table], checkfirst=True)
    
    drop_table('users')
    
    0 讨论(0)
  • 2020-12-02 16:04

    Just call drop() against the table object. From the docs:

    Issue a DROP statement for this Table, using the given Connectable for connectivity.

    In your case it should be:

    User.__table__.drop()
    

    If you get an exception like:

    sqlalchemy.exc.UnboundExecutionError: Table object 'my_users' is not bound to an Engine or Connection. Execution can not proceed without a database to execute against
    

    You need to pass the engine:

    User.__table__.drop(engine)
    
    0 讨论(0)
  • 2020-12-02 16:11

    Below is example code you can execute in iPython to test the creation and deletion of a table on Postgres

    from sqlalchemy import * # imports all needed modules from sqlalchemy
    
    engine = create_engine('postgresql://python:python@127.0.0.1/production') # connection properties stored
    
    metadata = MetaData() # stores the 'production' database's metadata
    
    users = Table('users', metadata,
    Column('user_id', Integer),
    Column('first_name', String(150)),
    Column('last_name', String(150)),
    Column('email', String(255)),
    schema='python') # defines the 'users' table structure in the 'python' schema of our connection to the 'production' db
    
    users.create(engine) # creates the users table
    
    users.drop(engine) # drops the users table
    

    You can also preview my article on Wordpress with this same example and screenshots: oscarvalles.wordpress.com (search for SQL Alchemy).

    0 讨论(0)
提交回复
热议问题