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

连接内存版SQLIte

python 复制代码
from sqlalchemy import create_engine

engine = create_engine('sqlite:///:memory:')
print(engine)

连接文件版SQLite

python 复制代码
from sqlalchemy import create_engine

engine = create_engine('sqlite:///sqlite3.db')
print(engine)

连接MySQL数据库

python 复制代码
from sqlalchemy import create_engine

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

根据模型自动创建表

python 复制代码
import enum
from datetime import datetime
from decimal import Decimal

import sqlalchemy
from sqlalchemy import create_engine, DateTime, func, String
from sqlalchemy.orm import Mapped, DeclarativeBase, mapped_column

engine = 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新增数据

python 复制代码
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添加数据

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

批量新增数据

python 复制代码
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查询

python 复制代码
with sessionmaker(engine).begin() as session:
    employee = session.get(Employee, 1)
    print(employee.name)

查询所有的数据

python 复制代码
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)

查询指定字段

python 复制代码
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:  # row
        print(employee.name, employee.age)

执行原生SQL语句进行查询

python 复制代码
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:  # row
        print(employee.name, employee.age)

根据ID修改数据

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

执行update方法

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

根据ID删除数据

python 复制代码
with sessionmaker(engine).begin() as session:
    employee = session.get(Employee, 1)
    session.delete(employee)

执行delete方法

python 复制代码
with sessionmaker(engine).begin() as session:
    query = sqlalchemy.delete(Employee).where(Employee.id == 2)
    session.execute(query)

执行is null查询

python 复制代码
with sessionmaker(engine).begin() as session:
    query = select(Employee).where(Employee.salary.is_(None))  # is null
    employees = session.execute(query).scalars()
    print(employees)

执行is not null查询

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

执行like模糊查询

python 复制代码
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查询

python 复制代码
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查询

python 复制代码
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)

求平均薪资

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

统计表中的数据个数

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

执行分页查询

python 复制代码
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)

执行排序查询

python 复制代码
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)

执行分组聚合查询

python 复制代码
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)
相关推荐
周全全2 分钟前
MySQL报错解决:The user specified as a definer (‘root‘@‘%‘) does not exist
android·数据库·mysql
Chef_Chen2 分钟前
从0开始机器学习--Day17--神经网络反向传播作业
python·神经网络·机器学习
白云如幻7 分钟前
MySQL的分组函数
数据库·mysql
千澜空22 分钟前
celery在django项目中实现并发任务和定时任务
python·django·celery·定时任务·异步任务
荒川之神22 分钟前
ORACLE 闪回技术简介
数据库·oracle
斯凯利.瑞恩29 分钟前
Python决策树、随机森林、朴素贝叶斯、KNN(K-最近邻居)分类分析银行拉新活动挖掘潜在贷款客户附数据代码
python·决策树·随机森林
yannan201903131 小时前
【算法】(Python)动态规划
python·算法·动态规划
蒙娜丽宁1 小时前
《Python OpenCV从菜鸟到高手》——零基础进阶,开启图像处理与计算机视觉的大门!
python·opencv·计算机视觉
光芒再现dev1 小时前
已解决,部署GPTSoVITS报错‘AsyncRequest‘ object has no attribute ‘_json_response_data‘
运维·python·gpt·语言模型·自然语言处理
好喜欢吃红柚子1 小时前
万字长文解读空间、通道注意力机制机制和超详细代码逐行分析(SE,CBAM,SGE,CA,ECA,TA)
人工智能·pytorch·python·计算机视觉·cnn