How to create a new database using SQLAlchemy?

前端 未结 4 1596
余生分开走
余生分开走 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:18

    It's possible to avoid manual transaction management while creating database by providing isolation_level='AUTOCOMMIT' to create_engine function:

    import sqlalchemy
    
    with sqlalchemy.create_engine(
        'postgresql:///postgres',
        isolation_level='AUTOCOMMIT'
    ).connect() as connection:
        connection.execute('CREATE DATABASE my_database')
    

    Also if you are not sure that database doesn't exist there is a way to ignore database creation error due to existence by suppressing sqlalchemy.exc.ProgrammingError exception:

    import contextlib
    import sqlalchemy.exc
    
    with contextlib.suppress(sqlalchemy.exc.ProgrammingError):
        # creating database as above
    

提交回复
热议问题