话不多说
目的:为了对接第三方表视图,需要知道表视图的字段结构,如名称,对应的表字段类型
实现结果如图:
直接上代码:
from sqlalchemy import create_engine, MetaData, select, text
from web import urlquote
DRIVER = "ODBC Driver 18 for SQL Server"
INSTANCENAME = "\SQLEXPRESS"
host='127.0.0.1'
pwd='xxxxxxxxxxx'
dbname='dbdbdbdb'
engine = create_engine(f"mssql+pyodbc://sa:{urlquote(pwd)}@{host}{INSTANCENAME}:1433/{dbname}?driver={DRIVER}&TrustServerCertificate=yes", fast_executemany=True)
# 查询所有的视图名称
views_query = text("""
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.VIEWS
WHERE TABLE_SCHEMA = 'dbo'
""")
with engine.connect() as conn:
result = conn.execute(views_query)
views = result.fetchall()
# 对于每个视图,查询其字段和字段类型
for view in views:
if 'vw_OrdersByTimestamp'==view['TABLE_NAME']:
view_name = view['TABLE_NAME']
columns_query = text("""
SELECT COLUMN_NAME, DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = :view_name AND TABLE_SCHEMA = 'dbo'
""")
result = conn.execute(columns_query, view_name=view_name)
columns = result.fetchall()
print(f"视图名称: {view_name}")
for column in columns:
print(f"列名: {column['COLUMN_NAME']}, 数据类型: {column['DATA_TYPE']}")
# 关闭数据库连接
engine.dispose()
以上未完,后续有待解决对应的物理表名称,物理表字段名称