我用 Sql 脚本添加 db.sqlite 数据 。
进入表格:
engine = create_engine('sqlite:///' + os.path.join(APP_ROOT, 'db.sqlite'))
session = scoped_session(sessionmaker(bind=engine))
metadata = MetaData()
metadata.reflect(engine)
Base = automap_base(metadata=metadata)
Base.prepare()
session.query(Base.classes[tablename])
db.sqlite 拥有由 sql 脚本创建的天体视图。 如何让天体查看 ?
2023-07-15
irina_ikonn
manager_view = Table("manager", metadata, autoload_with=engine)
# list view columns: "id", "name", etc.
print("manager_view columns:", [c.name for c in manager_view.columns])
with engine.connect() as conn:
stmt = (
select(manager_view)
.order_by(manager_view.c.id) # "id" is a column listed above
for row in conn.execute(stmt):
print(row.id, row.name) # "id", "name"
这只反映了单一的观点。
或者,用ORM的方式:
engine = create_engine(
DATABASE_URL,
Base: AutomapBase = automap_base()
# You have to add the view to `Base.metadata` first with a table,
# so reflection will work on it.
# You can also directly use the Table with Core like above.
Table(
"manager",
Base.metadata, # this is how the view is recognized
Column('id', Integer, primary_key=True), # PK is necessary
autoload_with=engine,
# Reflect all tables and get the Manager model:
Base.prepare(autoload_with=engine)
print("Classes reflected:", Base.classes.keys())
Manager = Base.classes.manager
# Use it as you normally would:
with Session(engine) as session:
for manager in session.scalars(select(Manager)):
print(manager.id, manager.name, manager.hire_date)
engine = create_engine('sqlite:///' + 'db.sqlite')
session = Session(engine)
metadata = MetaData()
metadata.reflect(engine)
QUERY_TO_DB = 'SELECT * FROM property_1, property_2'
class CreateView(Executable, ClauseElement):
def __init__(self, name, select):
self.name = name
self.select = select
@compiles(CreateView)
def visit_create_view(element, compiler, **kw):
return "CREATE VIEW %s AS %s" % (
element.name,
element.select)
with engine.connect() as conn, conn:
createview = CreateView('name_view', QUERY_TO_DB)
conn.execute(createview)
except Exception as e:
print('Failed to create view: ', e)