Fork me on GitHub

sqlalchemy语法

## sqlalchemy

返回参数时候一般使用 db.session.query()的方式(支持多表查询),也可以使用Modle.query()的方式(Moddle代表类名称,不支持多表查询 ),优先使用db.session.query()的方式

sqlalchemy的通用写法(直接复制到项目中即可)

from flask import  Flask
from sqlalchemy import create_engine,Column,Integer,String,DateTime,Table,MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker,session,scoped_session
from flask_sqlalchemy import SQLAlchemy

# 建立与Mysql的连接
engine = create_engine('mysql+pymysql://root:1234@localhost/blockchain')
# 定义模型类继承的父类以及数据连接会话
DBsession = sessionmaker(bind=engine)
dbsession = scoped_session(DBsession)
Base = declarative_base()
md = MetaData(bind=engine)


class User(Base):
    __table__ = Table('user_info',md,autoload=True)

    def member_list(self):
        result = dbsession.query(User).all()
        # result = dbsession.query(User).filter(User.username == 1).count()
        return result
#
# if __name__ == '__main__':
    # result = dbsession.query(User).all()
    # for row in result:
    #     print(row.username,row.telephone)

  基础查询汇总:

1、result = dbsession.query(Usrs).all()  #等价于select * from users
2、result = dbsession.query(Users.userid,Users.username).all()  #等价于select userid,username from users
3、 result = db.session.query(Users).filter_by(username=1,qq='1234567').all()  # select * from users where userid=1 and qq='1234567
4、result = dbsession.query(Users).filter(or_(User.suerid=7 or User.username=='丹尼')).all()   #select * from  users where userid=7 or username='丹尼'
5、result = dbsession.query(Users).limit(3).all()
# select * from users limit 3
result = dbsessioon.query(Users).limit(5).offset(3).all()
# select * from users limit 3,5
6、count = dbsession.query(Users).filter(Users.userid > 3).count()
# select count(*) from users where ....
7、 #去重:
result = dbsession.query(Users.qq).distinct(Users.qq).all()
8、#排序:
select * from users order by userid desc
result = dbsession.query(Users).order_by(Users.userid).all()
9、# select * from users where username like '%moumou'
result = dbsession.query(Users).filter(User.username.like('%moumou')).all()
10、分组查询:
reslut = dbsession.query(Users).group_by(Users.role).all()

多表连接查询:
多表连接查询时,返回的结果集不再是单纯的[data,data]数据结构,而是每张表的结果有独立的对象来维护
比如:用for循环进行遍历时:
for article,users in result:
    print(     )
多表查询:
result =  dbsession.query(Articles,Users).join(Users,Article.userid == Users.userid).all()

利用sqlalchemy执行原生的SQL:
result = dbsession.execute("select * from users where userid>5").fetchall()

  

 

posted @ 2021-01-27 00:09  sy-  阅读(156)  评论(0编辑  收藏  举报