SQLAlchemy - Getting a list of tables(SQLAlchemy - 获取表列表)
问题描述
我在文档中找不到任何关于此的信息,但是如何获取在 SQLAlchemy 中创建的表的列表?
我使用类方法来创建表.
所有的表都收集在 SQLAlchemy MetaData 对象的 tables 属性中.要获取这些表的名称列表:
如果您使用的是声明性扩展,那么您可能不会自己管理元数据.幸运的是,元数据仍然存在于基类中,
<预><代码>>>>Base = sqlalchemy.ext.declarative.declarative_base()>>>基础元数据元数据(无)如果您想弄清楚数据库中存在哪些表,即使是那些您甚至还没有告诉 SQLAlchemy 的表,那么您可以使用表反射.然后 SQLAlchemy 将检查数据库并使用所有缺失的表更新元数据.
<预><代码>>>>metadata.reflect(引擎)对于 Postgres,如果您有多个模式,则需要遍历引擎中的所有模式:
from sqlalchemy import inspect检查员 = 检查(引擎)schemas = inspector.get_schema_names()对于模式中的模式:打印(架构:%s"%架构)对于 inspector.get_table_names(schema=schema) 中的 table_name:对于 inspector.get_columns(table_name, schema=schema) 中的列:打印(列:%s"%列)I couldn't find any information about this in the documentation, but how can I get a list of tables created in SQLAlchemy?
I used the class method to create the tables.
All of the tables are collected in the tables attribute of the SQLAlchemy MetaData object. To get a list of the names of those tables:
>>> metadata.tables.keys()
['posts', 'comments', 'users']
If you're using the declarative extension, then you probably aren't managing the metadata yourself. Fortunately, the metadata is still present on the baseclass,
>>> Base = sqlalchemy.ext.declarative.declarative_base()
>>> Base.metadata
MetaData(None)
If you are trying to figure out what tables are present in your database, even among the ones you haven't even told SQLAlchemy about yet, then you can use table reflection. SQLAlchemy will then inspect the database and update the metadata with all of the missing tables.
>>> metadata.reflect(engine)
For Postgres, if you have multiple schemas, you'll need to loop thru all the schemas in the engine:
from sqlalchemy import inspect
inspector = inspect(engine)
schemas = inspector.get_schema_names()
for schema in schemas:
print("schema: %s" % schema)
for table_name in inspector.get_table_names(schema=schema):
for column in inspector.get_columns(table_name, schema=schema):
print("Column: %s" % column)
这篇关于SQLAlchemy - 获取表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQLAlchemy - 获取表列表
基础教程推荐
- 是否可以执行按位分组功能? 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 无法解决整理冲突 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
