Database Creation and Deletion Utility

  • Share this:

Code introduction


This function is used to create or drop a database based on the provided database string. If the database does not exist, it will create one; if it does exist, it will decide whether to create or drop based on the value of the `create` parameter.


Technology Stack : SQLAlchemy-Utils

Code Type : Database Management Function

Code Difficulty : Intermediate


                
                    
from sqlalchemy_utils import database_exists, create_database, drop_database

def create_or_drop_db(db_string, create=True):
    """
    Create or drop a database based on the provided database string.
    """
    engine = create_engine(db_string)
    if create:
        if not database_exists(engine.url):
            create_database(engine.url)
        else:
            print("Database already exists.")
    else:
        if database_exists(engine.url):
            drop_database(engine.url)
        else:
            print("Database does not exist.")