sqlalchemy获取数据库名、表名、字段名、字段类型

示例程序:

import configparser as cparser
from sqlalchemy import create_engine
import sqlalchemy

class ConnConfig():
    def __init__(self):
        # --------- 读取config.ini配置文件 ---------------
        cf = cparser.ConfigParser()
        cf.read('配置文件路径', encoding='UTF-8')
        self.HOST = cf.get("mysqlconf", "host")
        self.PORT = cf.get("mysqlconf", "port")
        self.USERNAME = cf.get("mysqlconf", "user")
        self.PASSWORD = cf.get("mysqlconf", "password")
        self.DATABASE = cf.get("mysqlconf", "db_name")
        self.DB_URI = 'mysql+pymysql://{}:{}@{}:{}/{}'.format(self.USERNAME, self.PASSWORD, self.HOST, self.PORT,
                                                              self.DATABASE)
        # 创建引擎
        self.engine = create_engine(self.DB_URI)
cf = ConnConfig()

# 获取数据库名列表
insp = sqlalchemy.inspect(cf.engine)
print(insp.get_schema_names())
# 获取表名列表
tables = cf.engine.table_names()
print(tables)
# 获取表字段列表
md = sqlalchemy.MetaData()
table  = sqlalchemy.Table('表名', md, autoload=True, autoload_with=cf.engine)
print(table.c)
print(table.c.字段名.type)

 

posted @ 2020-11-09 17:24  -零  阅读(3337)  评论(0编辑  收藏  举报