Sqlalchemy if表不存在

时间:2022-09-26 07:42:25

I wrote a module which is to 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 myexample.db database, and create tables to it if it doesn't already have that table.

但在另一个函数中,我想打开我的例子。db数据库,并为它创建表,如果它没有该表。

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

我将创建的第一个后续表将是:

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

(Since it is initially an empty database, it will have no tables in it, but subsequently, I can add more tables to it. Thats what i'm trying to say.)

(因为它最初是一个空数据库,所以里面没有表,但是随后,我可以向它添加更多的表。这就是我想说的。

Any suggestions?

有什么建议吗?

1 个解决方案

#1


21  

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.

我已经弄明白我打算做什么了。我用engine.dialect。has_table(engine, Variable_tableName)检查数据库中是否有该表。如果没有,那么它将继续在数据库中创建一个表。

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.

这似乎给了我我想要的。

#1


21  

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.

我已经弄明白我打算做什么了。我用engine.dialect。has_table(engine, Variable_tableName)检查数据库中是否有该表。如果没有,那么它将继续在数据库中创建一个表。

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.

这似乎给了我我想要的。