我想实现一个函数,该函数提供有关数据库中存在的所有表(及其表名)的信息(不仅限于使用SQLAlchemy创建的表)。在阅读文档时,在我看来这是通过反思完成的,但是我没有设法使某些事情起作用。有关如何执行此操作的任何建议或示例?
从引擎开始:
from sqlalchemy import create_engine
engine = create_engine("postgresql://u:p@host/database")
所有表/列名称的快速路径,请使用检查器:
from sqlalchemy import inspect
inspector = inspect(engine)
for table_name in inspector.get_table_names():
for column in inspector.get_columns(table_name):
print("Column: %s" % column['name'])
docs:http : //docs.sqlalchemy.org/en/rel_0_9/core/reflection.html? highlight= inspector# fine-grained-reflection-with- inspector
或者,使用元数据/表:
from sqlalchemy import MetaData
m = MetaData()
m.reflect(engine)
for table in m.tables.values():
print(table.name)
for column in table.c:
print(column.name)
docs:http : //docs.sqlalchemy.org/en/rel_0_9/core/reflection.html#reflecting-all-tables-at-once
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句