我正在尝试使用 sqlalchemy 的反射功能,但遇到了问题。
这是我要反映的 mysql 表。
| Country | CREATE TABLE `Country` (
`Code` varchar(8) NOT NULL,
`Country` varchar(64) NOT NULL,
`IsValid` varchar(1) DEFAULT 'Y',
PRIMARY KEY (`Code`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
反射代码(sch.py)。
from sqlalchemy.ext.declarative import declarative_base
import sqlalchemy
import eng
#Base = sqlalchemy.ext.declarative.declarative_base()
Base = declarative_base()
country = Table('Country',eng.Meta,autoload=True)
class Country(Base):
__tablename__ = country
__mapper_args = {
'primary_key' : [country.c.Code]
}
英语.py
import sqlalchemy
import sqlalchemy.orm
eng = sqlalchemy.create_engine('mysql://user:pass@host/db',echo=True)
Meta = sqlalchemy.MetaData()
Meta.bind = eng
sesDec = sqlalchemy.orm.sessionmaker(bind=eng)
当import sch
我得到错误。
import sqlalchemy
from sch import Country
import eng
ses = eng.sesDec()
res = ses.query(Country.Code.label('Code'),Country.Country.label('Country'))
for rec in res.filter(Country.IsValid == 'Y').filter(Country.Code.like('A%')).order_by(Country.Code).all():
print rec
错误(堆栈跟踪的底部)
File "/pythonlib/lib64/python2.4/site-packages/sqlalchemy/sql/expression.py", line 4198, in description
return self.name.encode('ascii', 'backslashreplace')
AttributeError: 'Table' object has no attribute 'encode