使用 SQLAlchemy 列出数据库表 [英] List database tables with SQLAlchemy
本文介绍了使用 SQLAlchemy 列出数据库表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想实现一个函数,该函数提供有关数据库中存在的所有表(及其列名)的信息(不仅是使用 SQLAlchemy 创建的表).在阅读文档时,在我看来这是通过反射完成的,但我没有设法使某些事情起作用.有关如何执行此操作的任何建议或示例?
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?
推荐答案
从引擎开始:
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)
文档:http://docs.sqlalchemy.org/en/rel_0_9/core/reflection.html#reflecting-all-tables-at-once
这篇关于使用 SQLAlchemy 列出数据库表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文