Sqlalchemy if table does not exist

后端 未结 4 646
南方客
南方客 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:12

    For those who define the table first in some models.table file, among other tables. This is a code snippet for finding the class that represents the table we want to create ( so later we can use the same code to just query it )

    But together with the if written above, I still run the code with checkfirst=True

    ORMTable.__table__.create(bind=engine, checkfirst=True)
    

    models.table

    class TableA(Base):
    class TableB(Base):
    class NewTableC(Base):
    
       id = Column('id', Text)
       name = Column('name', Text)
    

    form

    Then in the form action file:

    engine = create_engine("sqlite:///myexample.db")
    if not engine.dialect.has_table(engine, table_name):
       # Added to models.tables the new table I needed ( format Table as written above )
       table_models = importlib.import_module('models.tables')
    
       # Grab the class that represents the new table
       # table_name = 'NewTableC'
       ORMTable = getattr(table_models, table_name)            
    
       # checkfirst=True to make sure it doesn't exists
       ORMTable.__table__.create(bind=engine, checkfirst=True)
    

提交回复
热议问题