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 - 获取表列表


基础教程推荐
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01