How to delete a table in SQLAlchemy?

前端 未结 4 915
无人共我
无人共我 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 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).

提交回复
热议问题