使用SQLALCHEMY引擎获取表信息/元数据,例如表的update_time /上次更新时间

问题描述

我已成功通过from sqlalchemy import create_engine将Python连接到我的MysqL数据库

有了这个engine,我可以根据需要获取数据。

我正在使用 table_names = engine.table_names()获取数据库中的所有表名。

我最终需要的是表信息,例如#of条目,updated_time等。

我可以使用selects来完成所有操作,但是我想知道是否还有方便的函数,例如table_names()来做到这一点?

以下是我想用更方便的查询代替的查询

SELECT UPDATE_TIME
FROM   @R_794_4045@ion_schema.tables
WHERE  TABLE_NAME = 'my_table'

解决方法

您可以使用Inspector对象:

from sqlalchemy import create_engine
from sqlalchemy.engine import reflection

"""
initialize engine
"""

inspector = reflection.Inspector.from_engine(engine)
for table in inspector.get_table_names():
    print(inspector.get_columns(table))

这里是documentation to the reflection

要提取Inspector返回的值,您需要遍历各列:

for column in inspector.get_columns(table):
    print(column['name'])
    print(column['type'])
    print(column['nullable'])