SQLAlchemy ORM构建四步闭环:定义模型(继承Base、Column声明字段)、配置连接(create_engine+sessionmaker)、创建表(Base.metadata.create_all)、CRUD操作(session增删改查并commit)。

用 SQLAlchemy 构建 ORM 系统不难,关键是把几个核心环节串清楚:定义模型、配置连接、创建表、操作数据。下面按实际开发顺序一步步说清楚。
定义数据模型(Model)
模型就是 Python 类,对应数据库里的表。每个类继承 db.Model(Flask-SQLAlchemy)或直接用 Base(原生 SQLAlchemy),字段用 Column 定义,类型选对很关键。
比如用户表:
from sqlalchemy import Column, Integer, String, Boolean from sqlalchemy.ext.declarative import declarative_base <p>Base = declarative_base()</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/00968c3c2c15" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Python免费学习笔记(深入)</a>”;</p><p>class User(Base): <strong>tablename</strong> = 'users' id = Column(Integer, primary_key=True) name = Column(String(50), nullable=False) email = Column(String(120), unique=True) is_active = Column(Boolean, default=True)
登录后复制
注意点:
- 主键必须明确声明,否则报错
- String 要带长度(如 String(50)),SQLite 可忽略但其他库会报错
- nullable=False 控制 NOT NULL,unique=True 对应唯一索引
- 外键和关系后面再加,先跑通基础结构
配置数据库连接与初始化
连接字符串格式是:dialect+driver://username:password@host:port/database。本地开发常用 SQLite,简单省事:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
<p>engine = create_engine('sqlite:///app.db', echo=True) # echo=True 查看生成的 SQL
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
session = SessionLocal()
登录后复制
常见情况:
- PostgreSQL:postgresql://user:pass@localhost:5432/mydb
- MySQL:mysql+pymysql://user:pass@localhost:3306/mydb
- Windows 路径用正斜杠或双反斜杠,避免转义问题:'sqlite:///C:/myapp/app.db'
创建表(首次运行必做)
模型写好了,数据库里还没表。调用 Base.metadata.create_all(engine) 就能自动生成:
Base.metadata.create_all(engine)
登录后复制
这一步只建不存在的表,已有表不会被改动。开发中如果改了模型字段,不能靠它自动更新 —— 要么删库重来(调试期可用),要么用 alembic 做迁移。
标签: mysql word python windows app session ai win
还木有评论哦,快来抢沙发吧~