python - 在 SQLAlchemy 中获取表名

标签 python mysql sqlalchemy

from sqlalchemy import create_engine

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,Integer,String
from sqlalchemy.orm import sessionmaker

engine = create_engine('mysql://we0:go@wecom/javadb', convert_unicode=True, echo=False)
try:
   engine.execute("use javadb")
   engine.connect()
   print 'connected'
except:
   print 'error'

Base = declarative_base()

Session = sessionmaker(bind=engine)

session = Session()

print engine.table_names()
print Base.metadata.tables
#print Base.metadata.reflect(engine)
class MontEmp(Base):
    __table__ = Base.metadata.tables['MONTGOMERY_EMPLOYEE']

for item in session.query(MontEmp.id):
        print item

我试图从现有数据库中获取表名并查询它,但是当我尝试通过 Base.metadata.tables['MONTGOMERY_EMPLOYEE'] 访问该表时出现错误,我收到关键错误。

当我打印 Base.metadata.tables 时,它是空的,但当我打印 engine.table_names() 时,它列出了所有表。

问题:-

为什么 Base.metadata.tables['MONTGOMERY_EMPLOYEE'] 是空的?

最佳答案

我遇到了同样的问题,我就是这样解决的。

from sqlalchemy.schema import MetaData
from sqlalchemy import create_engine

engine = create_engine(config.DATABASE_URL)
meta = MetaData()
meta.reflect(bind=engine)

meta.tables.keys()   <== this is what we were looking for

关于python - 在 SQLAlchemy 中获取表名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31197709/

相关文章:

mysql - Django Mysql 连接池

mysql - map 表的 Rails 范围

php - mysql php私有(private)消息系统重复行

mysql - SQL查询检测带有特殊字符的列?

python - 为什么拥有一个未绑定(bind)到 SQLAlchemy 引擎的元数据对象很有用?

python - 类型错误 : can't compare offset-naive and offset-aware datetimes

python - pyCharm:依赖代码的应用程序的安全重构信息

python - 在 python 中的字典中移动引用的文件

python - Azure 应用程序服务 python 模块导入构建时出现错误

python - sqlalchemy 有像 django 中的 Q 一样的过滤器对象吗?