sql to sqlalchemy 实例教程
生活随笔
收集整理的這篇文章主要介紹了
sql to sqlalchemy 实例教程
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
在Python項(xiàng)目中,經(jīng)常需要操作數(shù)據(jù)庫(kù),而 sqlalchemy 提供了 SQL 工具包及對(duì)象關(guān)系映射(ORM)工具,大大提高了編程開(kāi)發(fā)的效率。為了更好的提升自己的 sql 以及使用 sqlachemy 水平,可以使用 MySQL 自帶的示范數(shù)據(jù)庫(kù) employees 進(jìn)行練習(xí)。
搭建基于 MySQL 實(shí)例數(shù)據(jù)庫(kù) employees 的 sqlalchemy 開(kāi)發(fā)環(huán)境
請(qǐng)參閱下面的鏈接內(nèi)容:
搭建基于 MySQL 實(shí)例數(shù)據(jù)庫(kù) employees 的 sqlalchemy 開(kāi)發(fā)環(huán)境
基本實(shí)例
以下九個(gè)例子全是以代碼加注釋的形式來(lái)展示給大家。
# -*- coding:utf-8 -*- __author__ = '東方鶚' __blog__ = 'http://www.os373.cn'from models import session, Employee, Department, DeptEmp, DeptManager, Salary, Title import operator'''----------------------------------------------第一例-----------------------------------------------功能說(shuō)明:使用主鍵對(duì) employees 表進(jìn)行查詢,結(jié)果是: 返回該主鍵對(duì)應(yīng)的單條數(shù)據(jù)! ''''''使用 sql 語(yǔ)句方式進(jìn)行查詢''' 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 方式進(jìn)行查詢''' 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)]'''比較兩個(gè)結(jié)果,應(yīng)該是True''' for d in zip(sql_data, alchemy_data):print(d) print('第一例結(jié)果是:{}'.format(operator.eq(sql_data, alchemy_data)))'''-------------------------------------------------------------------------------------------------''''''-------------------------------------------第二例--------------------------------------------------功能說(shuō)明:對(duì) employees 表進(jìn)行查詢,結(jié)果是:從第 4 行開(kāi)始查詢,返回之后的 10 行數(shù)據(jù)!值為一個(gè)列表。 ''''''使用 sql 語(yǔ)句方式進(jìn)行查詢''' 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 方式進(jìn)行查詢''' 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()]'''比較兩個(gè)結(jié)果,應(yīng)該是True''' for d in zip(sql_data, alchemy_data):print(d) print('第二例結(jié)果是:{}'.format(operator.eq(sql_data, alchemy_data)))'''-------------------------------------------------------------------------------------------------''''''-------------------------------------------第三例--------------------------------------------------功能說(shuō)明:使用一個(gè)精確參數(shù)對(duì) employees 表進(jìn)行查詢(搜索字段 last_name 為 'Nooteboom' 的內(nèi)容),結(jié)果是: 返回該參數(shù)對(duì)應(yīng)的第一條數(shù)據(jù)!僅僅是第一條數(shù)據(jù)! ''''''使用 sql 語(yǔ)句方式進(jìn)行查詢''' 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 方式進(jìn)行查詢''' 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)]'''比較兩個(gè)結(jié)果,應(yīng)該是True''' for d in zip(sql_data, alchemy_data):print(d) print('第三例結(jié)果是:{}'.format(operator.eq(sql_data, alchemy_data)))'''-------------------------------------------------------------------------------------------------''''''-------------------------------------------第四例--------------------------------------------------功能說(shuō)明:使用一個(gè)精確參數(shù)對(duì) employees 表進(jìn)行查詢(搜索字段 last_name 為 'Nooteboom' 的內(nèi)容),結(jié)果是: 返回該參數(shù)對(duì)應(yīng)的所有數(shù)據(jù)!所有數(shù)據(jù)!值為一個(gè)列表。 ''''''使用 sql 語(yǔ)句方式進(jìn)行查詢''' 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 方式進(jìn)行查詢''''''方法一 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()]'''比較兩個(gè)結(jié)果,應(yīng)該是True''' for d in zip(sql_data, alchemy_data):print(d) print('第四例結(jié)果是:{}'.format(operator.eq(sql_data, alchemy_data)))'''-------------------------------------------------------------------------------------------------''''''-------------------------------------------第五例--------------------------------------------------功能說(shuō)明:使用兩個(gè)及以上的精確參數(shù)對(duì) employees 表進(jìn)行查詢(搜索字段 last_name 為 'Nooteboom' 并且字段 first_name 為 'Pohua' 的內(nèi)容),結(jié)果是: 返回參數(shù)對(duì)應(yīng)的所有數(shù)據(jù)!所有數(shù)據(jù)!值為一個(gè)列表。 ''''''使用 sql 語(yǔ)句方式進(jìn)行查詢''' 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 方式進(jìn)行查詢''''''方法一 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()]'''比較兩個(gè)結(jié)果,應(yīng)該是True''' for d in zip(sql_data, alchemy_data):print(d) print('第五例結(jié)果是:{}'.format(operator.eq(sql_data, alchemy_data)))'''-------------------------------------------------------------------------------------------------''''''-------------------------------------------第六例--------------------------------------------------功能說(shuō)明:使用一個(gè)模糊參數(shù)對(duì) employees 表進(jìn)行查詢,結(jié)果是: 返回該參數(shù)對(duì)應(yīng)的所有數(shù)據(jù)!所有數(shù)據(jù)!值為一個(gè)列表。提示:1、sqlalchemy 提供了 like, endswith, startswith 函數(shù)結(jié)合通配符來(lái)進(jìn)行模糊查詢。對(duì)于 like, endswith, startswith ,見(jiàn)字如面,請(qǐng)按照英文字面意思理解。2、本例的重點(diǎn)是使用且僅一個(gè)模糊參數(shù), 主要是為了展示 like 函數(shù)。 ''''''使用 sql 語(yǔ)句方式進(jìn)行查詢''' 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 方式進(jìn)行查詢'''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()]'''比較兩個(gè)結(jié)果,應(yīng)該是True''' for d in zip(sql_data, alchemy_data):print(d) print('第六例結(jié)果是:{}'.format(operator.eq(sql_data, alchemy_data)))'''-------------------------------------------------------------------------------------------------''''''-------------------------------------------第七例--------------------------------------------------功能說(shuō)明:使用兩個(gè)及以上模糊參數(shù)對(duì) employees 表進(jìn)行查詢,查詢字段 last_name 近似于 'N%te_%',并且字段 first_name 在 ('Jaewon', 'os373.cn') 里,同時(shí),字段 birth_date 是以 1955 開(kāi)頭,且字段 hire_date 是以 05-30 結(jié)束的員工信息。結(jié)果是: 返回參數(shù)對(duì)應(yīng)的所有數(shù)據(jù)!所有數(shù)據(jù)!值為一個(gè)列表。提示:1、sqlalchemy 提供了 like, endswith, startswith 函數(shù)結(jié)合通配符來(lái)進(jìn)行模糊查詢。對(duì)于 like, endswith, startswith ,見(jiàn)字如面,請(qǐng)按照英文字面意思理解。2、本例的重點(diǎn)是展示 like, endswith, startswith 函數(shù)以及 and_, or_, in_ 邏輯運(yùn)算符函數(shù)的用法。彩蛋:思考一下 not in, not equal,is NULL,is not NULL 的用法。 ''''''使用 sql 語(yǔ)句方式進(jìn)行查詢''' 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 方式進(jìn)行查詢''' 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()]'''比較兩個(gè)結(jié)果,應(yīng)該是True''' for d in zip(sql_data, alchemy_data):print(d) print('第七例結(jié)果是:{}'.format(operator.eq(sql_data, alchemy_data)))'''-------------------------------------------------------------------------------------------------''''''-------------------------------------------第八例--------------------------------------------------功能說(shuō)明:使用兩個(gè)及以上模糊參數(shù)對(duì) employees 表進(jìn)行查詢,查詢字段 last_name 近似于 'N%te_%',并且字段 first_name 在 ('Jaewon', 'os373.cn') 里的員工信息,或者是,字段 birth_date 是以 1955 開(kāi)頭,且字段 hire_date 是以 05-30 結(jié)束的員工信息的個(gè)數(shù)。結(jié)果是: 返回一個(gè)數(shù)字。提示:1、sqlalchemy 提供了 like, endswith, startswith 函數(shù)結(jié)合通配符來(lái)進(jìn)行模糊查詢。對(duì)于 like, endswith, startswith ,見(jiàn)字如面,請(qǐng)按照英文字面意思理解。2、本例的重點(diǎn)是展示 like, endswith, startswith 函數(shù)以及 and_, or_, in_ 邏輯運(yùn)算符函數(shù)的用法。3、func 函數(shù)可以執(zhí)行數(shù)據(jù)庫(kù)所支持的函數(shù),本例中是為了執(zhí)行 MySQL 的 count 函數(shù)。4、scalar() 函數(shù)是為了返回單項(xiàng)數(shù)據(jù),與 first(), one() 函數(shù)類似,但是前者返回的是單項(xiàng)數(shù)據(jù),后兩者返回的是 tuple。 ''''''使用 sql 語(yǔ)句方式進(jìn)行查詢''' 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 方式進(jìn)行查詢''' 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()'''比較兩個(gè)結(jié)果,應(yīng)該是True''' print(sql_data, alchemy_data) print('第八例結(jié)果是:{}'.format(operator.eq(sql_data, alchemy_data)))'''-------------------------------------------------------------------------------------------------''''''-------------------------------------------第九例--------------------------------------------------功能說(shuō)明:使用兩個(gè)及以上模糊參數(shù)對(duì) employees 表進(jìn)行查詢,查詢字段 last_name 近似于 'N%te_%',并且字段 first_name 在 ('Jaewon', 'os373.cn') 里的員工信息,或者是,字段 birth_date 是以 1955 開(kāi)頭,且字段 hire_date 是以 05-30 結(jié)束的員工信息,并按照字段 last_name 進(jìn)行排序。結(jié)果是: 返回參數(shù)對(duì)應(yīng)的所有數(shù)據(jù)!所有數(shù)據(jù)!值為一個(gè)列表。提示:1、由于 MySQL 5.7 中的 sql_mode 設(shè)置有 only_full_group_by,因此要求 group by 的使用方法像 oracle 一樣,必須得把要查詢出的字段都羅列在 group by 語(yǔ)句之后,聚合函數(shù)除外。按照最靠前的字段來(lái)進(jìn)行排序。 ''''''使用 sql 語(yǔ)句方式進(jìn)行查詢''' 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 方式進(jìn)行查詢''' 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()]'''比較兩個(gè)結(jié)果,應(yīng)該是True''' for d in zip(sql_data, alchemy_data):print(d) print('第九例結(jié)果是:{}'.format(operator.eq(sql_data, alchemy_data)))'''-------------------------------------------------------------------------------------------------''' session.commit() session.close()其實(shí),這是本人維護(hù)的一個(gè) github 項(xiàng)目,歡迎大家能夠提供有意思的 SQL 語(yǔ)句,我們一起來(lái)將它轉(zhuǎn)換為 sqlalachemy 語(yǔ)句。
項(xiàng)目地址——https://eastossifrage.github.io/sql_to_sqlalchemy/
希望你能夠喜歡。
總結(jié)
以上是生活随笔為你收集整理的sql to sqlalchemy 实例教程的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。