How to create a new database using SQLAlchemy?

前端 未结 4 1581
余生分开走
余生分开走 2020-11-28 19:34

Using SQLAlchemy, an Engine object is created like this:

from sqlalchemy import create_engine
engine = create_engine(\"postgresql://localhost/mydb\")
         


        
4条回答
  •  眼角桃花
    2020-11-28 20:29

    SQLAlchemy-Utils provides custom data types and various utility functions for SQLAlchemy. You can install the most recent official version using pip:

    pip install sqlalchemy-utils
    

    The database helpers include a create_database function:

    from sqlalchemy import create_engine
    from sqlalchemy_utils import database_exists, create_database
    
    engine = create_engine("postgres://localhost/mydb")
    if not database_exists(engine.url):
        create_database(engine.url)
    
    print(database_exists(engine.url))
    

提交回复
热议问题