使用SQLAlchemy列出数据库表 [英] List database tables with SQLAlchemy
问题描述
我想实现一个函数,该函数提供有关数据库中存在的所有表(及其列名)的信息(不仅仅是使用SQLAlchemy创建的表)。在阅读文档时,在我看来,这是通过反射,但我没有设法得到一些工作。有关如何执行此操作的任何建议或示例?
使用引擎开始:
从sqlalchemy import create_engine
engine = create_engine(postgresql:// u:p @ host / database)
所有表/列名称的快速路径,使用检查器:
来自sqlalchemy import inspect
inspector = inspect(engine)
for table_name在inspector.get_table_names()中:
for inspector.get_columns :
print(Column:%s%column ['name'])
,使用MetaData / Tables:
来自sqlalchemy import MetaData
m = MetaData()
m.reflect引擎)
用于m.tables.values()中的表:
print(table.name)
用于table.c中的列:
print(column.name)
docs: http://docs.sqlalchemy.org/en/rel_0_9/core/reflection.html#reflecting-all-tables-at-once
I want to implement a function that gives information about all the tables (and their column names) that are present in a database (not only those created with SQLAlchemy). While reading the documentation it seems to me that this is done via reflection but I didn't manage to get something working. Any suggestions or examples on how to do this?
解决方案start with an engine:
from sqlalchemy import create_engine engine = create_engine("postgresql://u:p@host/database")
quick path to all table /column names, use an inspector:
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'])
alternatively, use MetaData / Tables:
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
这篇关于使用SQLAlchemy列出数据库表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!