当前位置:   article > 正文

flask---》更多查询方式/连表查询/原生sql(django-orm如何执行原生sql)/flask-sqlalchemy_flask sqlalchemy execute select原生sql

flask sqlalchemy execute select原生sql

更多查询方式

  1. #1 查询: filer:写条件 filter_by:等于的值
  2. # 查询所有 是list对象
  3. res = session.query(User).all() # 是个普通列表
  4. print(type(res))
  5. print(len(res))
  6. # 2 只查询某几个字段
  7. # select name as xx,email from user;
  8. res = session.query(User.name.label('xx'), User.email)
  9. # print(res) # 打出原生sql
  10. # # print(res.all())
  11. # for item in res.all():
  12. # print(item[0])
  13. # 3 filter传的是表达式,filter_by传的是参数
  14. res = session.query(User).filter(User.name == "lqz").all()
  15. res = session.query(User).filter(User.name != "lqz").all()
  16. res = session.query(User).filter(User.name != "lqz", User.email == '3@qq.com').all()
  17. #4 django 中使用 Q (与 或 非) 如果是, 就是and条件
  18. res = session.query(User).filter_by(name='lqz099').all()
  19. res = session.query(User).filter_by(name='lqz099',email='47@qq.com').all()
  20. # 5 取一个 all了后是list,list 没有first方法
  21. res = session.query(User).first()
  22. # 6查询所有,使用占位符(了解) :value :name
  23. # select * from user where id <20 or name=lqz
  24. res = session.query(User).filter(text("id<:value or name=:name")).params(value=20, name='lqz').all()
  25. # 7 自定义查询(了解)
  26. # from_statement 写纯原生sql
  27. res=session.query(User).from_statement(text("SELECT * FROM users where email=:email")).params(email='3@qq.com').all()
  28. print(type(res[0])) # 是book的对象,但是查的是User表 不要这样写
  29. print(res[0].name) #
  30. # 8 高级查询
  31. #  条件
  32. # 表达式,and条件连接
  33. res = session.query(User).filter(User.id > 1, User.name == 'lqz099').all() # and条件
  34. # between
  35. res = session.query(User).filter(User.id.between(1, 9), User.name == 'lqz099').all()
  36. res = session.query(User).filter(User.id.between(1, 9)).all()
  37. # in
  38. res = session.query(User).filter(User.id.in_([1,3,4])).all()
  39. res = session.query(User).filter(User.email.in_(['3@qq.com','r@qq.com'])).all()
  40. # ~非,除。。外
  41. res = session.query(User).filter(~User.id.in_([1,3,4])).all()
  42. print(res)
  43. # 二次筛选
  44. res = session.query(User).filter(~User.id.in_(session.query(User.id).filter_by(name='lqz'))).all()
  45. print(res)
  46. # and or条件
  47. from sqlalchemy import and_, or_
  48. # or_包裹的都是or条件,and_包裹的都是and条件
  49. res = session.query(User).filter(and_(User.id >= 3, User.name == 'lqz099')).all() # and条件
  50. res = session.query(User).filter(User.id < 3, User.name == 'lqz099').all() # 等同于上面
  51. res = session.query(User).filter(or_(User.id < 2, User.name == 'eric')).all()
  52. res = session.query(User).filter(or_(User.id < 2,and_(User.name == 'lqz099', User.id > 3),User.extra != ""))
  53. # 通配符,以e开头,不以e开头
  54. res = session.query(User).filter(User.email.like('%@%')).all()
  55. # select user.id from user where user.name not like e%;
  56. res = session.query(User.id).filter(~User.name.like('e%'))
  57. res = session.query(User).filter(~User.name.like('e%')).all()
  58. # 分页
  59. # 一页2条,查第5
  60. res = session.query(User)[2*5:2*5+2]
  61. # 排序,根据name降序排列(从大到小)
  62. res = session.query(User).order_by(User.email.desc()).all()
  63. res = session.query(Book).order_by(Book.price.desc()).all()
  64. res = session.query(Book).order_by(Book.price.asc()).all()
  65. # 第一个条件重复后,再按第二个条件升序排
  66. res = session.query(User).order_by(User.name.desc(), User.id.asc())
  67. # 分组查询 5个聚合函数
  68. from sqlalchemy.sql import func
  69. # 分组后,只能拿分组字段和聚合函数字典,如果拿别的,是严格模式,会报错
  70. res = session.query(User).group_by(User.extra) # 如果是严格模式,就报错
  71. # 分组之后取最大id,id之和,最小id 和分组的字段
  72. from sqlalchemy.sql import func
  73. res = session.query(
  74. User.name,
  75. func.max(User.id),
  76. func.sum(User.id),
  77. func.min(User.id),
  78. func.avg(User.id)).group_by(User.name).all()
  79. for item in res:
  80. print(item)
  81. # 分组后having
  82. # select name,max(id),sum(id),min(id) from user group by user.name having id_max>2;
  83. from sqlalchemy.sql import func
  84. res = session.query(
  85. User.name,
  86. func.max(User.id),
  87. func.sum(User.id),
  88. func.min(User.id)).group_by(User.name).having(func.max(User.id) > 2).all()
  89. print(res)

连表查询

  1. ### 关联关系,基于连表的跨表查询
  2. from models1 import Person,Hobby
  3. # 链表操作
  4. select * from person,hobby where person.hobby_id=hobby.id;
  5. res = session.query(Person, Hobby).filter(Person.hobby_id == Hobby.id).all()
  6. # 自己连表查询
  7. # join表,默认是inner join,自动按外键关联
  8. # select * from Person inner join Hobby on Person.hobby_id=Hobby.id;
  9. # res = session.query(Person).join(Hobby).all()
  10. #isouter=True 外连,表示Person left join Favor,没有右连接,反过来即可
  11. # select * from Person left join Hobby on Person.hobby_id=Hobby.id;
  12. # res = session.query(Person).join(Hobby, isouter=True).all()
  13. # 没有right join,通过这个实现
  14. # res = session.query(Hobby).join(Person, isouter=True).all()
  15. # # 自己指定on条件(连表条件),第二个参数,支持on多个条件,用and_,同上
  16. # select * from Person left join Hobby on Person.id=Hobby.id;
  17. # res = session.query(Person).join(Hobby, Person.hobby_id == Hobby.id, isouter=True) # sql本身有问题,只是给你讲, 自己指定链接字段
  18. # 右链接
  19. # print(res)
  20. # 多对多关系连表
  21. # 多对多关系,基于链表的跨表查
  22. # 多表链接
  23. #方式一:直接连
  24. #select * FROM boy, girl, boy2girl WHERE boy.id = boy2girl.boy_id AND girl.id = boy2girl.girl_id
  25. # res = session.query(Boy, Girl,Boy2Girl).filter(Boy.id == Boy2Girl.boy_id,Girl.id == Boy2Girl.girl_id)
  26. # 方式二:join连
  27. # SELECT* FROM boy INNER JOIN boy2girl ON boy.id = boy2girl.boy_id INNER JOIN girl ON girl.id = boy2girl.girl_id WHERE boy.id >= %(id_1)s
  28. res = session.query(Boy).join(Boy2Girl).join(Girl).filter(Boy.id>=2)
  29. print(res)

原生sql(django-orm如何执行原生sql)

sqlalchemy执行原生sql

  1. # 有的复杂sql 用orm写不出来---》用原生sql查询
  2. # 原生sql查询,查出的结果是对象
  3. # 原生sql查询,查询结果列表套元组
  4. from sqlalchemy.orm import sessionmaker, relationship
  5. from sqlalchemy import create_engine
  6. engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/db001", max_overflow=0, pool_size=5)
  7. Session = sessionmaker(bind=engine)
  8. session = Session()
  9. #### 执行原生sql方式一:
  10. # 查询方式一:
  11. # cursor = session.execute('select * from users')
  12. # result = cursor.fetchall()
  13. # print(result) #列表套元组
  14. # 添加
  15. # cursor = session.execute('insert into users(name,email) values(:name,:email)',
  16. # params={"name": 'lqz', 'email': '3333@qq.com'})
  17. # session.commit()
  18. # print(cursor.lastrowid)
  19. ###执行原生sql方式二(以后都用session操作---》socpe_session线程安全)一般不用
  20. # conn = engine.raw_connection()
  21. # cursor = conn.cursor()
  22. # cursor.execute(
  23. # "select * from app01_book"
  24. # )
  25. # result = cursor.fetchall()
  26. # 执行原生sql方式三:
  27. # res = session.query(User).from_statement(text("SELECT * FROM boy where name=:name")).params(name='lqz').all()
  28. session.close()

django执行原生sql

  1. # 执行完的结果映射到对象中---》上面讲的 方式三:
  2. from model import Book
  3. books_obj_list = Book.objects.raw('select distinct id, book_name from test_book')
  4. for book_obj in books_obj_list:
  5. print(book_obj.id, book_obj.book_name)
  6. # 纯原生sql
  7. from django.db import connection
  8. cur=connection.cursor()
  9. cur.execute('select distinct id, book_name from test_book')
  10. print(cur.fetch_all())
  11. cur.close()
  12. with connection.cursor() as cur:
  13. cur.execute('select distinct id, book_name from test_book')

flask-sqlalchemy

  1. # sqlalchemy 集成到flask中
  2. # 第三方: flask-sqlalchemy 封装了用起来,更简洁
  3. # 使用flask-sqlalchemy集成
  4. 1 导入 from flask_sqlalchemy import SQLAlchemy
  5. 2 实例化得到对象
  6. db = SQLAlchemy()
  7. 3 将db注册到app中
  8. db.init_app(app)
  9. 4 视图函数中使用session
  10. 全局的db.session # 线程安全的
  11. 5 models.py 中继承Model
  12. db.Model
  13. 6 写字段
  14. username = db.Column(db.String(80), unique=True, nullable=False)
  15. 7 配置文件中加入
  16. SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root@127.0.0.1:3306/ddd?charset=utf8"
  17. SQLALCHEMY_POOL_SIZE = 5
  18. SQLALCHEMY_POOL_TIMEOUT = 30
  19. SQLALCHEMY_POOL_RECYCLE = -1
  20. # 追踪对象的修改并且发送信号
  21. SQLALCHEMY_TRACK_MODIFICATIONS = False

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/521926
推荐阅读
相关标签
  

闽ICP备14008679号