资讯专栏INFORMATION COLUMN

sql to sqlalchemy 实例教程

timger / 1260人阅读

摘要:对于,见字如面,请按照英文字面意思理解。本例的重点是使用且仅一个模糊参数主要是为了展示函数。本例的重点是展示函数以及逻辑运算符函数的用法。函数可以执行数据库所支持的函数,本例中是为了执行的函数。

</>复制代码

  1. 在Python项目中,经常需要操作数据库,而 sqlalchemy 提供了 SQL 工具包及对象关系映射(ORM)工具,大大提高了编程开发的效率。为了更好的提升自己的 sql 以及使用 sqlachemy 水平,可以使用 MySQL 自带的示范数据库 employees 进行练习。
搭建基于 MySQL 实例数据库 employees 的 sqlalchemy 开发环境

请参阅下面的链接内容:

搭建基于 MySQL 实例数据库 employees 的 sqlalchemy 开发环境

基本实例

以下九个例子全是以代码加注释的形式来展示给大家。

</>复制代码

  1. # -*- coding:utf-8 -*-
  2. __author__ = "东方鹗"
  3. __blog__ = "http://www.os373.cn"
  4. from models import session, Employee, Department, DeptEmp, DeptManager, Salary, Title
  5. import operator
  6. """----------------------------------------------第一例-----------------------------------------------
  7. 功能说明:
  8. 使用主键对 employees 表进行查询,结果是: 返回该主键对应的单条数据!
  9. """
  10. """使用 sql 语句方式进行查询"""
  11. sql = "select * from employees where emp_no = 10006"
  12. sql_data = [(d.emp_no, d.birth_date, d.first_name, d.last_name, d.gender, d.hire_date) for d in session.execute(sql)]
  13. """使用 sqlalchemy 方式进行查询"""
  14. d = session.query(Employee).get(10006)
  15. alchemy_data = [(d.emp_no, d.birth_date, d.first_name, d.last_name, d.gender, d.hire_date)]
  16. """比较两个结果,应该是True"""
  17. for d in zip(sql_data, alchemy_data):
  18. print(d)
  19. print("第一例结果是:{}".format(operator.eq(sql_data, alchemy_data)))
  20. """-------------------------------------------------------------------------------------------------"""
  21. """-------------------------------------------第二例--------------------------------------------------
  22. 功能说明:
  23. 对 employees 表进行查询,结果是:从第 4 行开始查询,返回之后的 10 行数据!值为一个列表。
  24. """
  25. """使用 sql 语句方式进行查询"""
  26. sql = "select * from employees limit 10 offset 4"
  27. sql_data = [(d.emp_no, d.birth_date, d.first_name, d.last_name, d.gender, d.hire_date) for d in session.execute(sql)]
  28. """使用 sqlalchemy 方式进行查询"""
  29. alchemy_data = [(d.emp_no, d.birth_date, d.first_name, d.last_name, d.gender, d.hire_date)
  30. for d in session.query(Employee).limit(10).offset(4).all()]
  31. """比较两个结果,应该是True"""
  32. for d in zip(sql_data, alchemy_data):
  33. print(d)
  34. print("第二例结果是:{}".format(operator.eq(sql_data, alchemy_data)))
  35. """-------------------------------------------------------------------------------------------------"""
  36. """-------------------------------------------第三例--------------------------------------------------
  37. 功能说明:
  38. 使用一个精确参数对 employees 表进行查询(搜索字段 last_name 为 "Nooteboom" 的内容),
  39. 结果是: 返回该参数对应的第一条数据!仅仅是第一条数据!
  40. """
  41. """使用 sql 语句方式进行查询"""
  42. sql = "select * from employees where last_name = "Nooteboom" limit 1"
  43. sql_data = [(d.emp_no, d.birth_date, d.first_name, d.last_name, d.gender, d.hire_date) for d in session.execute(sql)]
  44. """使用 sqlalchemy 方式进行查询"""
  45. d = session.query(Employee).filter_by(last_name="Nooteboom").first()
  46. alchemy_data = [(d.emp_no, d.birth_date, d.first_name, d.last_name, d.gender, d.hire_date)]
  47. """比较两个结果,应该是True"""
  48. for d in zip(sql_data, alchemy_data):
  49. print(d)
  50. print("第三例结果是:{}".format(operator.eq(sql_data, alchemy_data)))
  51. """-------------------------------------------------------------------------------------------------"""
  52. """-------------------------------------------第四例--------------------------------------------------
  53. 功能说明:
  54. 使用一个精确参数对 employees 表进行查询(搜索字段 last_name 为 "Nooteboom" 的内容),
  55. 结果是: 返回该参数对应的所有数据!所有数据!值为一个列表。
  56. """
  57. """使用 sql 语句方式进行查询"""
  58. sql = "select * from employees where last_name = "Nooteboom""
  59. sql_data = [(d.emp_no, d.birth_date, d.first_name, d.last_name, d.gender, d.hire_date) for d in session.execute(sql)]
  60. """使用 sqlalchemy 方式进行查询"""
  61. """方法一
  62. alchemy_data = [(d.emp_no, d.birth_date, d.first_name, d.last_name, d.gender, d.hire_date)
  63. for d in session.query(Employee).filter_by(last_name="Nooteboom").all()]
  64. """
  65. """方法二如下"""
  66. alchemy_data = [(d.emp_no, d.birth_date, d.first_name, d.last_name, d.gender, d.hire_date)
  67. for d in session.query(Employee.emp_no, Employee.birth_date, Employee.first_name,
  68. Employee.last_name, Employee.gender, Employee.hire_date
  69. ).filter_by(last_name="Nooteboom").all()]
  70. """比较两个结果,应该是True"""
  71. for d in zip(sql_data, alchemy_data):
  72. print(d)
  73. print("第四例结果是:{}".format(operator.eq(sql_data, alchemy_data)))
  74. """-------------------------------------------------------------------------------------------------"""
  75. """-------------------------------------------第五例--------------------------------------------------
  76. 功能说明:
  77. 使用两个及以上的精确参数对 employees 表进行查询(搜索字段 last_name 为 "Nooteboom"
  78. 并且字段 first_name 为 "Pohua" 的内容),
  79. 结果是: 返回参数对应的所有数据!所有数据!值为一个列表。
  80. """
  81. """使用 sql 语句方式进行查询"""
  82. sql = "select * from employees where last_name = "Nooteboom" and first_name = "Pohua""
  83. sql_data = [(d.emp_no, d.birth_date, d.first_name, d.last_name, d.gender, d.hire_date) for d in session.execute(sql)]
  84. """使用 sqlalchemy 方式进行查询"""
  85. """方法一
  86. alchemy_data = [(d.emp_no, d.birth_date, d.first_name, d.last_name, d.gender, d.hire_date)
  87. for d in session.query(Employee).
  88. filter_by(last_name="Nooteboom", first_name="Pohua").all()]
  89. """
  90. """方法二如下"""
  91. alchemy_data = [(d.emp_no, d.birth_date, d.first_name, d.last_name, d.gender, d.hire_date)
  92. for d in session.query(Employee).filter(Employee.last_name=="Nooteboom").
  93. filter(Employee.first_name=="Pohua").all()]
  94. """比较两个结果,应该是True"""
  95. for d in zip(sql_data, alchemy_data):
  96. print(d)
  97. print("第五例结果是:{}".format(operator.eq(sql_data, alchemy_data)))
  98. """-------------------------------------------------------------------------------------------------"""
  99. """-------------------------------------------第六例--------------------------------------------------
  100. 功能说明:
  101. 使用一个模糊参数对 employees 表进行查询,结果是: 返回该参数对应的所有数据!所有数据!值为一个列表。
  102. 提示:
  103. 1、sqlalchemy 提供了 like, endswith, startswith 函数结合通配符来进行模糊查询。
  104. 对于 like, endswith, startswith ,见字如面,请按照英文字面意思理解。
  105. 2、本例的重点是使用且仅一个模糊参数, 主要是为了展示 like 函数。
  106. """
  107. """使用 sql 语句方式进行查询"""
  108. sql = "select * from employees where last_name like "N%te_%""
  109. sql_data = [(d.emp_no, d.birth_date, d.first_name, d.last_name, d.gender, d.hire_date) for d in session.execute(sql)]
  110. """使用 sqlalchemy 方式进行查询"""
  111. alchemy_data = [(d.emp_no, d.birth_date, d.first_name, d.last_name, d.gender, d.hire_date)
  112. for d in session.query(Employee).filter(Employee.last_name.like("N%te_%")).all()]
  113. """比较两个结果,应该是True"""
  114. for d in zip(sql_data, alchemy_data):
  115. print(d)
  116. print("第六例结果是:{}".format(operator.eq(sql_data, alchemy_data)))
  117. """-------------------------------------------------------------------------------------------------"""
  118. """-------------------------------------------第七例--------------------------------------------------
  119. 功能说明:
  120. 使用两个及以上模糊参数对 employees 表进行查询,查询字段 last_name 近似于 "N%te_%"
  121. 并且字段 first_name 在 ("Jaewon", "os373.cn") 里,同时,
  122. 字段 birth_date 是以 1955 开头,且字段 hire_date 是以 05-30 结束的员工信息。
  123. 结果是: 返回参数对应的所有数据!所有数据!值为一个列表。
  124. 提示:
  125. 1、sqlalchemy 提供了 like, endswith, startswith 函数结合通配符来进行模糊查询。
  126. 对于 like, endswith, startswith ,见字如面,请按照英文字面意思理解。
  127. 2、本例的重点是展示 like, endswith, startswith 函数以及 and_, or_, in_ 逻辑运算符函数的用法。
  128. 彩蛋:思考一下 not innot equal,is NULL,is not NULL 的用法。
  129. """
  130. """使用 sql 语句方式进行查询"""
  131. sql = """
  132. SELECT
  133. *
  134. FROM
  135. employees
  136. WHERE
  137. last_name LIKE "N%te_%"
  138. AND first_name IN ("Jaewon", "os373.cn")
  139. AND birth_date LIKE "1955%"
  140. AND hire_date LIKE "%05-30"
  141. """
  142. sql_data = [(d.emp_no, d.birth_date, d.first_name, d.last_name, d.gender, d.hire_date) for d in session.execute(sql)]
  143. """使用 sqlalchemy 方式进行查询"""
  144. from sqlalchemy import and_, or_
  145. alchemy_data = [(d.emp_no, d.birth_date, d.first_name, d.last_name, d.gender, d.hire_date)
  146. for d in session.query(Employee).filter(and_(Employee.last_name.like("N%te_%"),
  147. Employee.first_name.in_(["Jaewon","os373.cn"]),
  148. Employee.birth_date.startswith("1955"),
  149. Employee.hire_date.endswith("05-30"))).all()]
  150. """比较两个结果,应该是True"""
  151. for d in zip(sql_data, alchemy_data):
  152. print(d)
  153. print("第七例结果是:{}".format(operator.eq(sql_data, alchemy_data)))
  154. """-------------------------------------------------------------------------------------------------"""
  155. """-------------------------------------------第八例--------------------------------------------------
  156. 功能说明:
  157. 使用两个及以上模糊参数对 employees 表进行查询,查询字段 last_name 近似于 "N%te_%"
  158. 并且字段 first_name 在 ("Jaewon", "os373.cn") 里的员工信息,或者是,
  159. 字段 birth_date 是以 1955 开头,且字段 hire_date 是以 05-30 结束的员工信息的个数。
  160. 结果是: 返回一个数字。
  161. 提示:
  162. 1、sqlalchemy 提供了 like, endswith, startswith 函数结合通配符来进行模糊查询。
  163. 对于 like, endswith, startswith ,见字如面,请按照英文字面意思理解。
  164. 2、本例的重点是展示 like, endswith, startswith 函数以及 and_, or_, in_ 逻辑运算符函数的用法。
  165. 3、func 函数可以执行数据库所支持的函数,本例中是为了执行 MySQL 的 count 函数。
  166. 4scalar() 函数是为了返回单项数据,与 first(), one() 函数类似,
  167. 但是前者返回的是单项数据,后两者返回的是 tuple。
  168. """
  169. """使用 sql 语句方式进行查询"""
  170. sql = """
  171. SELECT
  172. count(*)
  173. FROM
  174. employees
  175. WHERE
  176. (
  177. last_name LIKE "N%te_%"
  178. AND first_name IN ("Jaewon", "os373.cn")
  179. )
  180. OR (
  181. birth_date LIKE "1955%"
  182. AND hire_date LIKE "%05-30"
  183. )
  184. """
  185. sql_data = [d for d in session.execute(sql)][0][0]
  186. """使用 sqlalchemy 方式进行查询"""
  187. from sqlalchemy import and_, or_
  188. """方法一
  189. alchemy_data = session.query(Employee).filter(or_(and_(Employee.last_name.like("N%te_%"),
  190. Employee.first_name.in_(["Jaewon","os373.cn"])),
  191. and_(Employee.birth_date.startswith("1955"),
  192. Employee.hire_date.endswith("05-30")))).count()
  193. """
  194. """方法二"""
  195. from sqlalchemy import func
  196. alchemy_data = session.query(func.count("*")).filter(or_(and_(Employee.last_name.like("N%te_%"),
  197. Employee.first_name.in_(["Jaewon","os373.cn"])),
  198. and_(Employee.birth_date.startswith("1955"),
  199. Employee.hire_date.endswith("05-30")))).scalar()
  200. """比较两个结果,应该是True"""
  201. print(sql_data, alchemy_data)
  202. print("第八例结果是:{}".format(operator.eq(sql_data, alchemy_data)))
  203. """-------------------------------------------------------------------------------------------------"""
  204. """-------------------------------------------第九例--------------------------------------------------
  205. 功能说明:
  206. 使用两个及以上模糊参数对 employees 表进行查询,查询字段 last_name 近似于 "N%te_%"
  207. 并且字段 first_name 在 ("Jaewon", "os373.cn") 里的员工信息,或者是,
  208. 字段 birth_date 是以 1955 开头,且字段 hire_date 是以 05-30 结束的员工信息,
  209. 并按照字段 last_name 进行排序。
  210. 结果是: 返回参数对应的所有数据!所有数据!值为一个列表。
  211. 提示:
  212. 1、由于 MySQL 5.7 中的 sql_mode 设置有 only_full_group_by,因此要求 group by 的使用方法像 oracle
  213. 一样,必须得把要查询出的字段都罗列在 group by 语句之后,聚合函数除外。按照最靠前的字段来进行排序。
  214. """
  215. """使用 sql 语句方式进行查询"""
  216. sql = """
  217. SELECT
  218. *
  219. FROM
  220. employees
  221. WHERE
  222. (
  223. last_name LIKE "N%te_%"
  224. AND first_name IN ("Jaewon", "os373.cn")
  225. )
  226. OR (
  227. birth_date LIKE "1955%"
  228. AND hire_date LIKE "%05-30"
  229. )
  230. GROUP BY
  231. last_name,
  232. gender,
  233. hire_date,
  234. emp_no,
  235. birth_date,
  236. first_name
  237. """
  238. sql_data = [(d.emp_no, d.birth_date, d.first_name, d.last_name, d.gender, d.hire_date) for d in session.execute(sql)]
  239. """使用 sqlalchemy 方式进行查询"""
  240. from sqlalchemy import and_, or_
  241. alchemy_data = [(d.emp_no, d.birth_date, d.first_name, d.last_name, d.gender, d.hire_date)
  242. for d in session.query(Employee).filter(or_(and_(Employee.last_name.like("N%te_%"),
  243. Employee.first_name.in_(["Jaewon","os373.cn"])),
  244. and_(Employee.birth_date.startswith("1955"),
  245. Employee.hire_date.endswith("05-30")))).
  246. group_by(Employee.last_name, Employee.gender, Employee.hire_date, Employee.emp_no,
  247. Employee.birth_date, Employee.first_name).all()]
  248. """比较两个结果,应该是True"""
  249. for d in zip(sql_data, alchemy_data):
  250. print(d)
  251. print("第九例结果是:{}".format(operator.eq(sql_data, alchemy_data)))
  252. """-------------------------------------------------------------------------------------------------"""
  253. session.commit()
  254. session.close()

其实,这是本人维护的一个 github 项目,欢迎大家能够提供有意思的 SQL 语句,我们一起来将它转换为 sqlalachemy 语句。
项目地址——https://eastossifrage.github.io/sql_to_sqlalchemy/

希望你能够喜欢。

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/44592.html

相关文章

  • 通过demo学习OpenStack开发所需的基础知识 -- 数据库(1)

    摘要:另外,项目在单元测试中使用的是的内存数据库,这样开发者运行单元测试的时候不需要安装和配置复杂的数据库,只要安装好就可以了。而且,数据库是保存在内存中的,会提高单元测试的速度。是实现层的基础。项目一般会使用数据库来运行单元测试。 OpenStack中的关系型数据库应用 OpenStack中的数据库应用主要是关系型数据库,主要使用的是MySQL数据库。当然也有一些NoSQL的应用,比如Ce...

    warnerwu 评论0 收藏0
  • Python之使用Pandas库实现MySQL数据库的读写

    摘要:本次分享将介绍如何在中使用库实现数据库的读写。提供了工具包及对象关系映射工具,使用许可证发行。模块实现了与不同数据库的连接,而模块则使得能够操作数据库。   本次分享将介绍如何在Python中使用Pandas库实现MySQL数据库的读写。首先我们需要了解点ORM方面的知识。 ORM技术   对象关系映射技术,即ORM(Object-Relational Mapping)技术,指的是把关...

    darcrand 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<