Python 3.x之数据库框架Sqlalchemy操作SQlite(续)
接着前面讲解的Sqlalchemy框架。再举个例子。
如下所示:
这个例子是参考别人的Code的。
- __author__ = 'minggxu9'
- import sqlalchemy
- from sqlalchemy import create_engine
- eng=create_engine('sqlite:///:memory:',echo=True)
- eng.execute("select 1").scalar()
- from sqlalchemy.ext.declarative import declarative_base
- Base=declarative_base()
- #########################################################
- from sqlalchemy import join,Table,MetaData,\
- select,func,\
- and_,\
- Column,ForeignKey,\
- Integer,String,Text,Binary
- from sqlalchemy.orm import deferred,mapper,\
- relationship,column_property,\
- object_session,\
- validates
- #########################################################
- metadata=MetaData()
- #########################################################
- class Book(Base):
- __tablename__='book'
- book_id=Column(Integer,primary_key=True)
- title=Column(String(200),nullable=False)
- summary=Column(String(2000))
- excerpt=deferred(Column(Text))
- photo1=deferred(Column(Binary),group='photos')
- photo2=deferred(Column(Binary),group='photos')
- photo3=deferred(Column(Binary),group='photos')
- class Address(Base):
- __tablename__='address'
- id=Column(Integer,primary_key=True)
- user_id=Column(Integer,ForeignKey('user.id'))
- class User(Base):
- __tablename__='user'
- id=Column(Integer,primary_key=True)
- firstname=Column(String(50))
- lastname=Column(String(50))
- #fullname=column_property(firstname+' '+lastname)
- #address_count = column_property(
- # select([func.count(Address.id)]).\
- # where(Address.user_id==id)
- #)
- addresses=relationship("Address")
- @validates('addresses')
- def validate_address(self,key,address):
- assert '@' in address.email
- return address
- @property
- def fullname(self):
- return self.firstname+' '+self.lastname
- @property
- def address_count(self):
- return object_session(self).\
- scalar(select([func.count(Address.id)]).\
- where(Address.user_id==self.id))
- #########################################################
- Base.metadata.create_all(eng)
- #ed1_user=User('ed1','Ed1 Jones','ed1spassword')
- #ed2_user=User('ed2','Ed2 Jones','ed2spassword')
- #print("-----------------------")
- #from sqlalchemy.orm import Session
- #ses=Session(bind=eng)
- #ses.add(ed1_user)
- #ses.add(ed2_user)
- #ses.commit()
相关推荐
IT之家 2020-03-11
graseed 2020-10-28
zbkyumlei 2020-10-12
SXIAOYI 2020-09-16
jinhao 2020-09-07
impress 2020-08-26
liuqipao 2020-07-07
淡风wisdon大大 2020-06-06
yoohsummer 2020-06-01
chenjia00 2020-05-29
baike 2020-05-19
扭来不叫牛奶 2020-05-08
hxmilyy 2020-05-11
黎豆子 2020-05-07
xiongweiwei00 2020-04-29
Cypress 2020-04-25
冰蝶 2020-04-20