Sqlalchemy if the table does not exist

I wrote a module that should create an empty database file

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

But in another function, I want to open the myexample.db database and create tables for it, if it does not already have this table.

EG of the first, subsequent table that I would create:

 Table(Variable_TableName, metadata, Column('Id', Integer, primary_key=True, nullable=False), Column('Date', Date), Column('Volume', Float)) 

(Since this is initially an empty database, there will be no tables in it, but later on I can add more tables to it. What I'm trying to say.)

Any suggestions?

+25
python sqlalchemy
source share
2 answers

I managed to figure out what I was going to do. I used engine.dialect.has_table(engine, Variable_tableName) to check if there is a table in the database. If this is not the case, then he will proceed to create the table in the database.

Code example:

 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() 

It seems to give me what I'm looking for.

+45
source share

Note that the Baseametadata documentation says create_all:

By default, it will not try to recreate tables already present in the target database.

And if you see that create_all takes the following arguments: create_all (self, bind = None, tables = None, checkfirst = True) and as per the documentation:

By default, True, do not create CREATE for tables already present in the target database.

So if I understand your question correctly, you can simply skip the condition.

+8
source share

All Articles