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)
相关推荐
h***59331 小时前
MySQL如何执行.sql 文件:详细教学指南
数据库·mysql
郑重其事,鹏程万里1 小时前
键值存储数据库(chronicle-map)
数据库·oracle
Doro再努力1 小时前
【MySQL数据库09】外键约束与多表查询基础
数据库·mysql
头发还在的女程序员1 小时前
三天搞定招聘系统!附完整源码
开发语言·python
温轻舟1 小时前
Python自动办公工具06-设置Word文档中表格的格式
开发语言·python·word·自动化工具·温轻舟
ss2731 小时前
019:深入解析可重入互斥锁:原理、实现与线程安全实践
java·数据库·redis
花酒锄作田1 小时前
[python]FastAPI-Tracking ID 的设计
python·fastapi
高级程序源2 小时前
springboot社区医疗中心预约挂号平台app-计算机毕业设计源码16750
java·vue.js·spring boot·mysql·spring·maven·mybatis
AI-智能2 小时前
别啃文档了!3 分钟带小白跑完 Dify 全链路:从 0 到第一个 AI 工作流
人工智能·python·自然语言处理·llm·embedding·agent·rag
O***Z6162 小时前
三分钟内快速完成MySQL到达梦数据库的迁移
数据库·mysql