sqlalchemy 数据库多表操作(python语言)
#!/user/bin/python
# -*- encoding:utf-8 -*-
from sqlalchemy import *
from sqlalchemy.orm import *
engine=create_engine("sqlite:///./test.db")
metadata=MetaData()
party=Table('party',metadata,
Column('id',Integer,primary_key=True),
Column('name',String(32),nullable=False),
Column('type',String(32),nullable=False),
)
person=Table('person',metadata,
Column('id',Integer,ForeignKey('party.id'),primary_key=True),
Column('sex',String(15),nullable=False),
Column('email',String(100),nullable=False)
)
org=Table('org',metadata,
Column('id',Integer,ForeignKey('party.id'),primary_key=True),
Column('address',String(500),nullable=False)
)
#a=str(org.insert())
#print a
metadata.drop_all(engine)
metadata.create_all(engine)
class Party(object):
pass
class Org(Party):
pass
class Person(Party):
pass
mapper(Party,party,polymorphic_on=party.c.type,
polymorphic_identity="party")
mapper(Org,org,inherits=Party,
polymorphic_identity="org")
mapper(Person,person,inherits=Party,
polymorphic_identity="person")
p=Party()
p.name='name'
p.type='type'
o=Org()
o.name='orgName'
o.address='orgAddress'
#o.type="org"
Session=sessionmaker(bind=engine)
s=Session()
s.add(p)
s.add(o)
s.commit()
for r in s.query(Org).all():
print r.id,r.name,r.address,r.type