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 - 获取表列表
基础教程推荐
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 在多列上分布任意行 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- oracle区分大小写的原因? 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
