Python使用SQLAlchemy查询所有表名

就这么一个简单的问题居然在百度查不到答案,无奈去翻了文档,发现也存在一些版本更新的不同,记录一下。

官方文档在这里

更改的地方就是基类需要reflect对应的engine

Base = declarative_base()
        engine = create_engine('sqlite:///path',echo=True)
        Base.metadata.reflect(engine)
        tables = Base.metadata.tables
        print(tables)

tables是一个immutabledict,格式如下:

immutabledict({'users': Table('users', MetaData(bind=None), Column('id', INTEGER(), table=, primary_key=True, nullable=False), Column('name', VARCHAR(), table=), Column('fullname', VARCHAR(), table=), Column('password', VARCHAR(), table=), schema=None)})

经测试这个immutabledict没有has_key()方法,但是可以用if ‘users’ in tables.keys()判断

你可能感兴趣的:(python)