Python Sqlalchemy如果表不存在
我写了一个模块,创建一个空的数据库文件Python Sqlalchemy如果表不存在,python,sqlalchemy,Python,Sqlalchemy,我写了一个模块,创建一个空的数据库文件 def create_database(): engine = create_engine("sqlite:///myexample.db", echo=True) metadata = MetaData(engine) metadata.create_all() 但在另一个函数中,我想打开myexample.db数据库,如果它还没有那个表,就为它创建表 例如,我将创建的第一个后续表是: Table(Variable_TableN
def create_database():
engine = create_engine("sqlite:///myexample.db", echo=True)
metadata = MetaData(engine)
metadata.create_all()
但在另一个函数中,我想打开myexample.db
数据库,如果它还没有那个表,就为它创建表
例如,我将创建的第一个后续表是:
Table(Variable_TableName, metadata,
Column('Id', Integer, primary_key=True, nullable=False),
Column('Date', Date),
Column('Volume', Float))
(因为它最初是一个空数据库,所以里面没有表,但随后,我可以向其中添加更多表。这就是我想说的。)
有什么建议吗?我已经设法弄清楚我打算做什么了。我使用
engine.dialogue.has\u table(engine,Variable\u tableName)
检查数据库中是否有表如果没有,则它将继续在数据库中创建一个表
示例代码:
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()
这似乎给了我想要的东西。请注意,在“Base.metadata”中,它说明了如何创建所有: 默认情况下,将不会尝试重新创建表 存在于目标数据库中 如果您可以看到create_all接受以下参数:create_all(self,bind=None,tables=None,checkfirst=True),根据文档: 默认为True,不为中已存在的表发出CREATEs 目标数据库
因此,如果我正确理解了您的问题,您可以跳过条件。对于那些在一些
模型中首先定义表的人。表
文件以及其他表。
这是一段代码片段,用于查找表示要创建的表的类(因此稍后我们可以使用相同的代码来查询它)
但是与上面写的if
一起,我仍然使用checkfirst=True运行代码
ORMTable.__table__.create(bind=engine, checkfirst=True)
模型表
形式
然后以动作文件的形式:
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)
engine.Dialogue.has_表在cx_oracle上不适用于我。
我得到的是AttributeError:“OracleDialante\u cx\u oracle”对象没有属性“default\u schema\u name”
我编写了一个变通函数:
from sqlalchemy.engine.base import Engine
def orcl_tab_or_view_exists(in_engine: Engine, in_object: str, in_object_name: str,)-> bool:
"""Checks if Oracle table exists in current in_engine connection
in_object: 'table' | 'view'
in_object_name: table_name | view_name
"""
obj_query = """SELECT {o}_name FROM all_{o}s WHERE owner = SYS_CONTEXT ('userenv', 'current_schema') AND {o}_name = '{on}'
""".format(o=in_object, on=in_object_name.upper())
with in_engine.connect() as connection:
result = connection.execute(obj_query)
return len(list(result)) > 0
您要做的是数据库迁移。你应该考虑一下。这是一个python数据库迁移包,用于SQLAlchemy。我必须在has\u table
调用中添加schema='dbo'
,才能在MS上工作SQL@lowtech在代码的哪一部分添加“dbo”?目前,我在询问MSSQL中的一个表时遇到问题。@VIX如果不是engine.dialogue.has_table(engine,Variable_tableName,schema='dbo')
使用SQLAlchemy v1.2.11,engine.dialogue.has_table(engine,tableName)
不存在。然而,engine.has_table(tableName)
做得很好:)这是不必要的,因为@Belle05的答案表明,create_all()
有一个可选参数checkfirst
,默认为True
。如果设置,则仅当表尚不存在时才创建表。
from sqlalchemy.engine.base import Engine
def orcl_tab_or_view_exists(in_engine: Engine, in_object: str, in_object_name: str,)-> bool:
"""Checks if Oracle table exists in current in_engine connection
in_object: 'table' | 'view'
in_object_name: table_name | view_name
"""
obj_query = """SELECT {o}_name FROM all_{o}s WHERE owner = SYS_CONTEXT ('userenv', 'current_schema') AND {o}_name = '{on}'
""".format(o=in_object, on=in_object_name.upper())
with in_engine.connect() as connection:
result = connection.execute(obj_query)
return len(list(result)) > 0