Sqlalchemy if table does not exist

后端 未结 4 694
南方客
南方客 2021-01-31 14:28

I wrote a module which is to create an empty database file

def create_database():
    engine = create_engine(\"sqlite:///myexample.db\", echo=True)
    metadata          


        
4条回答
  •  不要未来只要你来
    2021-01-31 15:04

    I've managed to figure out what I intended to do. I used engine.dialect.has_table(engine, Variable_tableName) to check if the database has the table inside. IF it doesn't, then it will proceed to create a table in the database.

    Sample code:

    engine = create_engine("sqlite:///myexample.db")  # Access the DB Engine
    if not engine.dialect.has_table(engine, Variable_tableName):  # If table don't exist, Create.
        metadata = MetaData(engine)
        # Create a table with the appropriate Columns
        Table(Variable_tableName, metadata,
              Column('Id', Integer, primary_key=True, nullable=False), 
              Column('Date', Date), Column('Country', String),
              Column('Brand', String), Column('Price', Float),
        # Implement the creation
        metadata.create_all()
    

    This seems to be giving me what i'm looking for.

提交回复
热议问题