Python操作数据库的ORM框架SQLAlchemy快速入门教程

2024-09-01 17:44

本文主要是介绍Python操作数据库的ORM框架SQLAlchemy快速入门教程,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

连接内存版SQLIte

from sqlalchemy import create_engineengine = create_engine('sqlite:///:memory:')
print(engine)

连接文件版SQLite

from sqlalchemy import create_engineengine = create_engine('sqlite:///sqlite3.db')
print(engine)

连接MySQL数据库

from sqlalchemy import create_engineengine = create_engine('mysql+pymysql://root:zhangdapeng520@127.0.0.1:3306/fastzdp_sqlalchemy?charset=utf8')
print(engine)

根据模型自动创建表


import enum
from datetime import datetime
from decimal import Decimalimport sqlalchemy
from sqlalchemy import create_engine, DateTime, func, String
from sqlalchemy.orm import Mapped, DeclarativeBase, mapped_columnengine = create_engine('mysql+pymysql://root:zhangdapeng520@127.0.0.1:3306/fastzdp_sqlalchemy?charset=utf8')class BaseModel(DeclarativeBase):"""基础模型"""id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)create_time: Mapped[datetime] = mapped_column(DateTime, insert_default=func.now(), comment="创建时间")update_time: Mapped[datetime] = mapped_column(DateTime, insert_default=func.now(), onupdate=func.now(),comment="更新时间")class GenderEnum(enum.Enum):MALE = "男"FEMALE = "女"class Employee(BaseModel):"""员工模型,对应员工表"""__tablename__ = 'employee'name: Mapped[str] = mapped_column(String(36), index=True, nullable=False, comment="姓名")age: Mapped[int] = mapped_column(comment="年龄")salary: Mapped[Decimal] = mapped_column(sqlalchemy.DECIMAL, nullable=False, comment="薪资")bonus: Mapped[float] = mapped_column(sqlalchemy.FLOAT, default=0, comment="奖金")is_leave: Mapped[bool] = mapped_column(sqlalchemy.Boolean, default=False, comment="是否离职")gender: Mapped[GenderEnum] = mapped_column(sqlalchemy.String(6), default=GenderEnum.MALE, comment="性别")if __name__ == '__main__':BaseModel.metadata.drop_all(engine)BaseModel.metadata.create_all(engine)

通过session新增数据

with Session(engine) as session:session.begin()try:session.add(Employee(name="张三", age=23, salary=Decimal(30000),gender=GenderEnum.MALE.value))except:session.rollback()session.commit()

通过sessionmaker添加数据

with sessionmaker(engine).begin() as session:session.add(Employee(name="李四", age=23, salary=Decimal(30000), gender=GenderEnum.MALE.value))

批量新增数据

with sessionmaker(engine).begin() as session:employees = [Employee(name="张三1", age=23, salary=Decimal(30000), gender=GenderEnum.MALE.value),Employee(name="张三2", age=23, salary=Decimal(30000), gender=GenderEnum.MALE.value),Employee(name="张三3", age=23, salary=Decimal(30000), gender=GenderEnum.MALE.value),]session.add_all(employees)

根据ID查询

with sessionmaker(engine).begin() as session:employee = session.get(Employee, 1)print(employee.name)

查询所有的数据

with sessionmaker(engine).begin() as session:query = select(Employee)data = session.scalars(query).all()print(data)for employee in data:print(employee.name, employee.age)

查询指定字段


with sessionmaker(engine).begin() as session:query = select(Employee.id, Employee.name, Employee.age)data = session.execute(query).all()print(data)for employee in data:  # rowprint(employee.name, employee.age)

执行原生SQL语句进行查询


with sessionmaker(engine).begin() as session:query = sqlalchemy.text("select id,name,age from employee")data = session.execute(query).all()print(data)for employee in data:  # rowprint(employee.name, employee.age)

根据ID修改数据


with sessionmaker(engine).begin() as session:employee = session.get(Employee, 1)employee.name = "张三333"

执行update方法


with sessionmaker(engine).begin() as session:query = sqlalchemy.update(Employee).where(Employee.id == 1).values(name="张三", age=33)session.execute(query)

根据ID删除数据

with sessionmaker(engine).begin() as session:employee = session.get(Employee, 1)session.delete(employee)

执行delete方法

with sessionmaker(engine).begin() as session:query = sqlalchemy.delete(Employee).where(Employee.id == 2)session.execute(query)

执行is null查询

with sessionmaker(engine).begin() as session:query = select(Employee).where(Employee.salary.is_(None))  # is nullemployees = session.execute(query).scalars()print(employees)

执行is not null查询

with sessionmaker(engine).begin() as session:query = select(Employee).where(Employee.salary.isnot(None))  # is not nullemployees = session.execute(query).scalars()print(employees)for employee in employees:print(employee.name, employee.age, employee.salary, employee.bonus, employee.is_leave)

执行like模糊查询

with sessionmaker(engine).begin() as session:query = select(Employee).where(Employee.name.like("%3"))  # like 模糊查询employees = session.execute(query).scalars()print(employees)for employee in employees:print(employee.name, employee.age, employee.salary, employee.bonus, employee.is_leave)

执行in查询


with sessionmaker(engine).begin() as session:query = select(Employee).where(Employee.id.in_([3, 5]))  # in 查询employees = session.execute(query).scalars()print(employees)for employee in employees:print(employee.name, employee.age, employee.salary, employee.bonus, employee.is_leave)

执行or查询

with sessionmaker(engine).begin() as session:query = select(Employee).where(sqlalchemy.or_(Employee.age < 20, Employee.age > 30))  # or 查询employees = session.execute(query).scalars()print(employees)for employee in employees:print(employee.name, employee.age, employee.salary, employee.bonus, employee.is_leave)

求平均薪资

with sessionmaker(engine).begin() as session:query = select(func.avg(Employee.salary))avg = session.execute(query).first()print(avg)

统计表中的数据个数

with sessionmaker(engine).begin() as session:query = select(func.count(Employee.id))id_count = session.execute(query).first()print(id_count)

执行分页查询

with sessionmaker(engine).begin() as session:query = select(Employee).offset(2).limit(2)data = session.execute(query).scalars()for employee in data:print(employee.id, employee.name)

执行排序查询

with sessionmaker(engine).begin() as session:# query = select(Employee).order_by(Employee.age.desc()) # 降序query = select(Employee).order_by(Employee.age)  # 升序data = session.execute(query).scalars()for employee in data:print(employee.id, employee.name, employee.age)

执行分组聚合查询

with sessionmaker(engine).begin() as session:query = select(Employee.gender, func.count(Employee.id)).group_by(Employee.gender)data = session.execute(query).all()for row in data:print(row.gender, row.count)

这篇关于Python操作数据库的ORM框架SQLAlchemy快速入门教程的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1127621

相关文章

Python基于wxPython和FFmpeg开发一个视频标签工具

《Python基于wxPython和FFmpeg开发一个视频标签工具》在当今数字媒体时代,视频内容的管理和标记变得越来越重要,无论是研究人员需要对实验视频进行时间点标记,还是个人用户希望对家庭视频进行... 目录引言1. 应用概述2. 技术栈分析2.1 核心库和模块2.2 wxpython作为GUI选择的优

Mysql表的简单操作(基本技能)

《Mysql表的简单操作(基本技能)》在数据库中,表的操作主要包括表的创建、查看、修改、删除等,了解如何操作这些表是数据库管理和开发的基本技能,本文给大家介绍Mysql表的简单操作,感兴趣的朋友一起看... 目录3.1 创建表 3.2 查看表结构3.3 修改表3.4 实践案例:修改表在数据库中,表的操作主要

C# WinForms存储过程操作数据库的实例讲解

《C#WinForms存储过程操作数据库的实例讲解》:本文主要介绍C#WinForms存储过程操作数据库的实例,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、存储过程基础二、C# 调用流程1. 数据库连接配置2. 执行存储过程(增删改)3. 查询数据三、事务处

Java使用Curator进行ZooKeeper操作的详细教程

《Java使用Curator进行ZooKeeper操作的详细教程》ApacheCurator是一个基于ZooKeeper的Java客户端库,它极大地简化了使用ZooKeeper的开发工作,在分布式系统... 目录1、简述2、核心功能2.1 CuratorFramework2.2 Recipes3、示例实践3

Java利用JSONPath操作JSON数据的技术指南

《Java利用JSONPath操作JSON数据的技术指南》JSONPath是一种强大的工具,用于查询和操作JSON数据,类似于SQL的语法,它为处理复杂的JSON数据结构提供了简单且高效... 目录1、简述2、什么是 jsONPath?3、Java 示例3.1 基本查询3.2 过滤查询3.3 递归搜索3.4

springboot security快速使用示例详解

《springbootsecurity快速使用示例详解》:本文主要介绍springbootsecurity快速使用示例,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝... 目录创www.chinasem.cn建spring boot项目生成脚手架配置依赖接口示例代码项目结构启用s

Python如何使用__slots__实现节省内存和性能优化

《Python如何使用__slots__实现节省内存和性能优化》你有想过,一个小小的__slots__能让你的Python类内存消耗直接减半吗,没错,今天咱们要聊的就是这个让人眼前一亮的技巧,感兴趣的... 目录背景:内存吃得满满的类__slots__:你的内存管理小助手举个大概的例子:看看效果如何?1.

Python+PyQt5实现多屏幕协同播放功能

《Python+PyQt5实现多屏幕协同播放功能》在现代会议展示、数字广告、展览展示等场景中,多屏幕协同播放已成为刚需,下面我们就来看看如何利用Python和PyQt5开发一套功能强大的跨屏播控系统吧... 目录一、项目概述:突破传统播放限制二、核心技术解析2.1 多屏管理机制2.2 播放引擎设计2.3 专

Python中随机休眠技术原理与应用详解

《Python中随机休眠技术原理与应用详解》在编程中,让程序暂停执行特定时间是常见需求,当需要引入不确定性时,随机休眠就成为关键技巧,下面我们就来看看Python中随机休眠技术的具体实现与应用吧... 目录引言一、实现原理与基础方法1.1 核心函数解析1.2 基础实现模板1.3 整数版实现二、典型应用场景2

Python实现无痛修改第三方库源码的方法详解

《Python实现无痛修改第三方库源码的方法详解》很多时候,我们下载的第三方库是不会有需求不满足的情况,但也有极少的情况,第三方库没有兼顾到需求,本文将介绍几个修改源码的操作,大家可以根据需求进行选择... 目录需求不符合模拟示例 1. 修改源文件2. 继承修改3. 猴子补丁4. 追踪局部变量需求不符合很