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)
相关推荐
Mr_Xuhhh1 小时前
GUI自动化测试--自动化测试的意义和应用场景
python·集成测试
2301_764441332 小时前
水星热演化核幔耦合数值模拟
python·算法·数学建模
循环过三天2 小时前
3.4、Python-集合
开发语言·笔记·python·学习·算法
你想考研啊2 小时前
oracle导出 导入
数据库·oracle
Q_Q5110082852 小时前
python+django/flask的眼科患者随访管理系统 AI智能模型
spring boot·python·django·flask·node.js·php
SunnyDays10114 小时前
如何使用Python高效转换Excel到HTML
python·excel转html
韩立学长4 小时前
基于Springboot的旧时月历史论坛4099k6s9(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
数据库·spring boot·后端
Q_Q5110082854 小时前
python+django/flask的在线学习系统的设计与实现 积分兑换礼物
spring boot·python·django·flask·node.js·php
Q_Q5110082855 小时前
python+django/flask的车辆尾气检测排放系统-可视化大屏展示
spring boot·python·django·flask·node.js·php
汤姆yu5 小时前
2026版基于python大数据的旅游可视化及推荐系统
python·旅游·大数据旅游