Python Sqlalchemy 如果表不存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33053241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:41:08  来源:igfitidea点击:

Sqlalchemy if table does not exist

pythonsqlalchemy

提问by jake wong

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.dbdatabase, and create tables to it if it doesn't already have that table.

但是在另一个函数中,我想打开myexample.db数据库,如果它还没有该表,则为其创建表。

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

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

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?

有什么建议?

采纳答案by jake wong

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. IFit 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.

这似乎给了我我正在寻找的东西。

回答by Belle05

Note that in 'Base.metadata' documentationit states about create_all:

请注意,在“Base.metadata”文档中,它说明了 create_all:

Conditional by default, will not attempt to recreate tables already present in the target database.

默认情况下有条件,不会尝试重新创建目标数据库中已经存在的表。

And if you can see that create_all takes these arguments: create_all(self, bind=None, tables=None, checkfirst=True), and according to documentation:

如果您可以看到 create_all 接受以下参数:create_all(self, bind=None, tables=None, checkfirst=True),并且根据文档:

Defaults to True, don't issue CREATEs for tables already present in the target database.

默认为 True,不要为目标数据库中已经存在的表发出 CREATE。

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

所以如果我正确理解你的问题,你可以跳过条件。

回答by Ricky Levi

For those who define the table first in some models.tablefile, 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 )

对于那些首先在某个models.table文件中定义表的人,以及其他表。这是一个代码片段,用于查找代表我们要创建的表的类(以便稍后我们可以使用相同的代码来查询它)

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

但是加上if上面写的,我还是用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)