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

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

请参阅下面的链接内容:

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

基本实例

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

# -*- coding:utf-8 -*-
__author__ = '东方鹗'
__blog__ = 'http://www.os373.cn'from models import session, Employee, Department, DeptEmp, DeptManager, Salary, Title
import operator'''----------------------------------------------第一例-----------------------------------------------功能说明:使用主键对 employees 表进行查询,结果是: 返回该主键对应的单条数据!
''''''使用 sql 语句方式进行查询'''
sql = "select * from employees where emp_no = 10006"
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)]'''使用 sqlalchemy 方式进行查询'''
d = session.query(Employee).get(10006)
alchemy_data = [(d.emp_no, d.birth_date, d.first_name, d.last_name, d.gender, d.hire_date)]'''比较两个结果,应该是True'''
for d in zip(sql_data, alchemy_data):print(d)
print('第一例结果是:{}'.format(operator.eq(sql_data, alchemy_data)))'''-------------------------------------------------------------------------------------------------''''''-------------------------------------------第二例--------------------------------------------------功能说明:对 employees 表进行查询,结果是:从第 4 行开始查询,返回之后的 10 行数据!值为一个列表。
''''''使用 sql 语句方式进行查询'''
sql = "select * from employees limit 10 offset 4"
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)]'''使用 sqlalchemy 方式进行查询'''
alchemy_data = [(d.emp_no, d.birth_date, d.first_name, d.last_name, d.gender, d.hire_date)for d in session.query(Employee).limit(10).offset(4).all()]'''比较两个结果,应该是True'''
for d in zip(sql_data, alchemy_data):print(d)
print('第二例结果是:{}'.format(operator.eq(sql_data, alchemy_data)))'''-------------------------------------------------------------------------------------------------''''''-------------------------------------------第三例--------------------------------------------------功能说明:使用一个精确参数对 employees 表进行查询(搜索字段 last_name 为 'Nooteboom' 的内容),结果是: 返回该参数对应的第一条数据!仅仅是第一条数据!
''''''使用 sql 语句方式进行查询'''
sql = "select * from employees where last_name = 'Nooteboom' limit 1"
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)]'''使用 sqlalchemy 方式进行查询'''
d = session.query(Employee).filter_by(last_name='Nooteboom').first()
alchemy_data = [(d.emp_no, d.birth_date, d.first_name, d.last_name, d.gender, d.hire_date)]'''比较两个结果,应该是True'''
for d in zip(sql_data, alchemy_data):print(d)
print('第三例结果是:{}'.format(operator.eq(sql_data, alchemy_data)))'''-------------------------------------------------------------------------------------------------''''''-------------------------------------------第四例--------------------------------------------------功能说明:使用一个精确参数对 employees 表进行查询(搜索字段 last_name 为 'Nooteboom' 的内容),结果是: 返回该参数对应的所有数据!所有数据!值为一个列表。
''''''使用 sql 语句方式进行查询'''
sql = "select * from employees where last_name = 'Nooteboom'"
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)]'''使用 sqlalchemy 方式进行查询''''''方法一
alchemy_data = [(d.emp_no, d.birth_date, d.first_name, d.last_name, d.gender, d.hire_date)for d in session.query(Employee).filter_by(last_name='Nooteboom').all()]
''''''方法二如下'''
alchemy_data = [(d.emp_no, d.birth_date, d.first_name, d.last_name, d.gender, d.hire_date)for d in session.query(Employee.emp_no, Employee.birth_date, Employee.first_name,Employee.last_name, Employee.gender, Employee.hire_date).filter_by(last_name='Nooteboom').all()]'''比较两个结果,应该是True'''
for d in zip(sql_data, alchemy_data):print(d)
print('第四例结果是:{}'.format(operator.eq(sql_data, alchemy_data)))'''-------------------------------------------------------------------------------------------------''''''-------------------------------------------第五例--------------------------------------------------功能说明:使用两个及以上的精确参数对 employees 表进行查询(搜索字段 last_name 为 'Nooteboom' 并且字段 first_name 为 'Pohua' 的内容),结果是: 返回参数对应的所有数据!所有数据!值为一个列表。
''''''使用 sql 语句方式进行查询'''
sql = "select * from employees where last_name = 'Nooteboom' and first_name = 'Pohua'"
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)]'''使用 sqlalchemy 方式进行查询''''''方法一
alchemy_data = [(d.emp_no, d.birth_date, d.first_name, d.last_name, d.gender, d.hire_date)for d in session.query(Employee).filter_by(last_name='Nooteboom', first_name='Pohua').all()]
'''
'''方法二如下'''
alchemy_data = [(d.emp_no, d.birth_date, d.first_name, d.last_name, d.gender, d.hire_date)for d in session.query(Employee).filter(Employee.last_name=='Nooteboom').filter(Employee.first_name=='Pohua').all()]'''比较两个结果,应该是True'''
for d in zip(sql_data, alchemy_data):print(d)
print('第五例结果是:{}'.format(operator.eq(sql_data, alchemy_data)))'''-------------------------------------------------------------------------------------------------''''''-------------------------------------------第六例--------------------------------------------------功能说明:使用一个模糊参数对 employees 表进行查询,结果是: 返回该参数对应的所有数据!所有数据!值为一个列表。提示:1、sqlalchemy 提供了 like, endswith, startswith 函数结合通配符来进行模糊查询。对于 like, endswith, startswith ,见字如面,请按照英文字面意思理解。2、本例的重点是使用且仅一个模糊参数, 主要是为了展示 like 函数。
''''''使用 sql 语句方式进行查询'''
sql = "select * from employees where last_name like 'N%te_%'"
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)]'''使用 sqlalchemy 方式进行查询'''alchemy_data = [(d.emp_no, d.birth_date, d.first_name, d.last_name, d.gender, d.hire_date)for d in session.query(Employee).filter(Employee.last_name.like('N%te_%')).all()]'''比较两个结果,应该是True'''
for d in zip(sql_data, alchemy_data):print(d)
print('第六例结果是:{}'.format(operator.eq(sql_data, alchemy_data)))'''-------------------------------------------------------------------------------------------------''''''-------------------------------------------第七例--------------------------------------------------功能说明:使用两个及以上模糊参数对 employees 表进行查询,查询字段 last_name 近似于 'N%te_%',并且字段 first_name 在 ('Jaewon', 'os373.cn') 里,同时,字段 birth_date 是以 1955 开头,且字段 hire_date 是以 05-30 结束的员工信息。结果是: 返回参数对应的所有数据!所有数据!值为一个列表。提示:1、sqlalchemy 提供了 like, endswith, startswith 函数结合通配符来进行模糊查询。对于 like, endswith, startswith ,见字如面,请按照英文字面意思理解。2、本例的重点是展示 like, endswith, startswith 函数以及 and_, or_, in_ 逻辑运算符函数的用法。彩蛋:思考一下 not in, not equal,is NULL,is not NULL 的用法。
''''''使用 sql 语句方式进行查询'''
sql = """SELECT*FROMemployeesWHERElast_name LIKE 'N%te_%'AND first_name IN ('Jaewon', 'os373.cn')AND birth_date LIKE '1955%'AND hire_date LIKE '%05-30'
"""
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)]'''使用 sqlalchemy 方式进行查询'''
from sqlalchemy import and_, or_
alchemy_data = [(d.emp_no, d.birth_date, d.first_name, d.last_name, d.gender, d.hire_date)for d in session.query(Employee).filter(and_(Employee.last_name.like('N%te_%'),Employee.first_name.in_(['Jaewon','os373.cn']),Employee.birth_date.startswith('1955'),Employee.hire_date.endswith('05-30'))).all()]'''比较两个结果,应该是True'''
for d in zip(sql_data, alchemy_data):print(d)
print('第七例结果是:{}'.format(operator.eq(sql_data, alchemy_data)))'''-------------------------------------------------------------------------------------------------''''''-------------------------------------------第八例--------------------------------------------------功能说明:使用两个及以上模糊参数对 employees 表进行查询,查询字段 last_name 近似于 'N%te_%',并且字段 first_name 在 ('Jaewon', 'os373.cn') 里的员工信息,或者是,字段 birth_date 是以 1955 开头,且字段 hire_date 是以 05-30 结束的员工信息的个数。结果是: 返回一个数字。提示:1、sqlalchemy 提供了 like, endswith, startswith 函数结合通配符来进行模糊查询。对于 like, endswith, startswith ,见字如面,请按照英文字面意思理解。2、本例的重点是展示 like, endswith, startswith 函数以及 and_, or_, in_ 逻辑运算符函数的用法。3、func 函数可以执行数据库所支持的函数,本例中是为了执行 MySQL 的 count 函数。4、scalar() 函数是为了返回单项数据,与 first(), one() 函数类似,但是前者返回的是单项数据,后两者返回的是 tuple。
''''''使用 sql 语句方式进行查询'''
sql = """SELECTcount(*)FROMemployeesWHERE(last_name LIKE 'N%te_%'AND first_name IN ('Jaewon', 'os373.cn'))OR (birth_date LIKE '1955%'AND hire_date LIKE '%05-30')
"""
sql_data = [d for d in session.execute(sql)][0][0]'''使用 sqlalchemy 方式进行查询'''
from sqlalchemy import and_, or_'''方法一
alchemy_data = session.query(Employee).filter(or_(and_(Employee.last_name.like('N%te_%'),Employee.first_name.in_(['Jaewon','os373.cn'])),and_(Employee.birth_date.startswith('1955'),Employee.hire_date.endswith('05-30')))).count()''''''方法二'''
from sqlalchemy import func
alchemy_data = session.query(func.count("*")).filter(or_(and_(Employee.last_name.like('N%te_%'),Employee.first_name.in_(['Jaewon','os373.cn'])),and_(Employee.birth_date.startswith('1955'),Employee.hire_date.endswith('05-30')))).scalar()'''比较两个结果,应该是True'''
print(sql_data, alchemy_data)
print('第八例结果是:{}'.format(operator.eq(sql_data, alchemy_data)))'''-------------------------------------------------------------------------------------------------''''''-------------------------------------------第九例--------------------------------------------------功能说明:使用两个及以上模糊参数对 employees 表进行查询,查询字段 last_name 近似于 'N%te_%',并且字段 first_name 在 ('Jaewon', 'os373.cn') 里的员工信息,或者是,字段 birth_date 是以 1955 开头,且字段 hire_date 是以 05-30 结束的员工信息,并按照字段 last_name 进行排序。结果是: 返回参数对应的所有数据!所有数据!值为一个列表。提示:1、由于 MySQL 5.7 中的 sql_mode 设置有 only_full_group_by,因此要求 group by 的使用方法像 oracle 一样,必须得把要查询出的字段都罗列在 group by 语句之后,聚合函数除外。按照最靠前的字段来进行排序。
''''''使用 sql 语句方式进行查询'''
sql = """SELECT*FROMemployeesWHERE(last_name LIKE 'N%te_%'AND first_name IN ('Jaewon', 'os373.cn'))OR (birth_date LIKE '1955%'AND hire_date LIKE '%05-30')GROUP BYlast_name,gender,hire_date,emp_no,birth_date,first_name
"""
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)]'''使用 sqlalchemy 方式进行查询'''
from sqlalchemy import and_, or_
alchemy_data = [(d.emp_no, d.birth_date, d.first_name, d.last_name, d.gender, d.hire_date)for d in session.query(Employee).filter(or_(and_(Employee.last_name.like('N%te_%'),Employee.first_name.in_(['Jaewon','os373.cn'])),and_(Employee.birth_date.startswith('1955'),Employee.hire_date.endswith('05-30')))).\group_by(Employee.last_name, Employee.gender, Employee.hire_date, Employee.emp_no,Employee.birth_date, Employee.first_name).all()]'''比较两个结果,应该是True'''
for d in zip(sql_data, alchemy_data):print(d)
print('第九例结果是:{}'.format(operator.eq(sql_data, alchemy_data)))'''-------------------------------------------------------------------------------------------------'''
session.commit()
session.close()

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

希望你能够喜欢。

sql to sqlalchemy 实例教程相关推荐

  1. sql server与java实例_Origin数据处理实例教程50节02040101

    本期小电分享50节Origin数据处理实例教程 链接:https://pan.baidu.com/s/1y-5wrJ6PEswKV_UMrJ_hYw 提取码:8suu 第1节- Origin图表中如何 ...

  2. sql python 教程_Python SQLAlchemy ORM教程(3)

    由于SQLAlchemy 中文资料比较少,所以根据官网给的tutorial外加其他大佬写的中文资料整合以后准备写一个SQLAlchemy 系列的基础入门教程.本系列可能会夹杂一些个人对于python ...

  3. 2018年又传喜报!热烈祝贺王家林大师大数据经典著作《Spark SQL大数据实例开发教程》 畅销书籍 出版上市!

    2018年又传喜报!热烈祝贺王家林大师大数据经典著作<Spark SQL大数据实例开发教程> 畅销书籍 出版上市! 作者: 王家林 段智华  条码书号:9787111591979 出版日期 ...

  4. smarty实例教程

    一.什么是smarty? smarty是一个使用PHP写出来的模板PHP模板引擎,它提供了逻辑与外在内容的分离,简单的讲,目的就是要使用PHP程序员同美工分离,使用的程序员改变程序的逻辑内容不会影响到 ...

  5. SQL 2008升级SQL 2008 R2完全教程或者10.00.1600升级10.50.1600

    今天将由于需要就将我的SQL 2008升级到SQL 2008 R2. 说到为什么要升级是因为,从另一台机器上备份了一个数据库,到我的机器上还原的时候提示"System.Data.SqlCli ...

  6. php100例代码教程,php实例代码_php用户登录实例教程代码

    摘要 腾兴网为您分享:php用户登录实例教程代码,音恋,小米云盘,武魂传说,万步有约等软件知识,以及绿城党旗红,一席app,一亩田app,窝立方,fairuse4wm,超星阅读,大连农商银行,qq名片 ...

  7. mysql主备数据库配置文档_MySQL数据库配置主从服务器实现双机热备实例教程

    网站:bbs.osyunwei.com 程序在:Web服务器192.168.21.129上面 数据库在:MySQL服务器192.168.21.169上面 实现目的:增加一台MySQL备份服务器(192 ...

  8. python3连接sql server数据库_Python3操作SQL Server数据库(实例讲解)

    1.前言 前面学完了SQL Server的基本语法,接下来学习如何在程序中使用sql,毕竟不能在程序中使用的话,实用性就不那么大了. 2.最基本的SQL查询语句 python是使用pymssql这个模 ...

  9. Python SQLAlchemy入门教程

    原文:https://www.cnblogs.com/ybjourney/p/11832045.html Python SQLAlchemy入门教程 一.介绍 关于ORM 为什么用sqlalchemy ...

最新文章

  1. SQL中使用WITH AS提高性能-使用公用表表达式(CTE)简化嵌套SQL
  2. 解决用navicate远程连接数据库出现1045 access denied for user 'root'@'localhost' using password yes...
  3. Kotlin实战指南八:高阶函数
  4. redis 内存不足 排查_一文深入了解 Redis 内存模型,Redis 的快是有原因的!
  5. 转-Apache kafka 工作原理介绍
  6. jQuery实现多个MP3音频播放
  7. 使用sharepoint自带的文本编辑器2
  8. leetcode python3 简单题206. Reverse Linked List
  9. centos7远程访问mysql数据库_CentOS7下安装mysql最快捷方式及mysql远程访问连接实现详解...
  10. 矩阵论7,8,9作业
  11. php毕设周记_毕设周记(一)
  12. Windows/Linux/Mac OS下IntelliJ IDEA快捷键中文大全(本人翻译自官方ReferenceCard.pdf)(PDF典藏版)
  13. Separating Pebbles数学,暴力
  14. python MDI窗口加载ui文件方法
  15. 自己的小程序修修补补
  16. 利用npm bin创建可执行命令实现项目代码规范自动化
  17. 所有域名都需要实名认证吗?域名实名认证有什么好处?
  18. UG NX 10 草图之草图基准设置
  19. 使用WinRT OCR API的WPF中的OCR
  20. 字符集、ASCII、Unicode

热门文章

  1. mysql如何explan优化sql_《MySQL数据库》MySQL 优化SQL(explain)
  2. 计组-控制器的功能和工作原理
  3. 7-二路归并排序C实现(递增递减的简单转换)
  4. php网站404页面302,404页面该怎么做?
  5. python列表常用方法_python之 列表常用方法
  6. OGNL是Object-Graph Navigation Language
  7. eclipse如何部署到tomcat上的
  8. java之spring mvc之初始spring mvc
  9. LS-DYNA常用关键字
  10. Python初识与简介【开篇】