环境:python 2.7
1、引入数据库连接及创建session工厂。相应代码如下:
import sys
defaultencoding ='utf-8'
if sys.getdefaultencoding() != defaultencoding:
reload(sys)
sys.setdefaultencoding(defaultencoding)
from sqlalchemyimport engine, create_engine
from sqlalchemy.ormimport sessionmaker
url="mysql+pymysql://root:root@localhost:3306/tj?charset=utf8"
engine=create_engine(url,echo=False,encoding="utf-8")
SessionClass=sessionmaker(bind=engine)#利用工厂模式获取SessionClass
session=SessionClass()#创建session对象,此时已绑定数据库引擎,但是未关联任何的对象模型
2、session 简单使用
(1)对于多表连接:join
videoExt,videoFile 实体名称
session.query(videoExt).join(videoFile,videoFile.id==videoExt.id).all()
sql:select * from video inner join videofile on videofile.id=videoExt.id
(2)条件 where
多个条件用逗号分隔
session.query(audio).filter(audio.status==0,XXX==XXXX,XXX==XXXX)
sql:select * from audio where audio.status=0 and xxx=xxxx....
(注‘或’运算符需引入 or_:from sqlalchemyimport or_ )
session.query(videoFile).filter(or_(videoFile.state=='0',videoFile.wealth_id=='2')).all()
sql:select * from videofile where state=0 or wealthid=2
(3)排序 order by
session.query(videoFile).order_by(videoFile.state,videoFile.wealth_id).all()
sql:select * from videofile order by state ,wealth_id
(注‘desc’排序符需引入 from sqlalchemyimport desc )
session.query(videoFile).order_by(desc(videoFile.state),videoFile.wealth_id).all()
(4) 分组,别名 group ,as
session.query(videoFile,func.max(videoFile.id).label("id"),func.sum(videoFile.id).label("ids")).filter(videoFile.state==1).group_by(videoFile.id).all()
SELECT max(id) AS id, sum(ids) AS ids FROM video WHERE state= 0 GROUP BY id
(5)自定义查询 (直接写sql)
finish=session.execute(" select * from video where id=1 and ....)
#获取数据 finish.fetchall()
网友评论