0. 前言
- 对象关系映射(Object Relational Mapping,简称ORM)模式是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术
- 简单的说,ORM是通过使用描述对象和数据库之间映射的元数据,将程序中的对象自动持久化到关系数据库中。Sqlalchemy 就是一种 ORM 框架
- 每个表会对应一个 Model 类,这些 Model 类都需要继承一个名为 declarative base class 的基类。我们需要通过下面的代码来获得这个基类:
from sqlalchemy.ext.declarative import declarative_base BASE = declarative_base()
-
有了这个基类,就可以定义各个表的 Model 类了:
class User(BASE): __tablename__ = "users" id = Column(INTEGER, primary_key=True) name = Column(CHAR(127)) password = Column(CHAR(127))
- 然后添加记录:
from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine ENGINE = create_engine("mysql://root:zaq12wsx@localhost:3306/mydb?charset=utf8", convert_unicode=True) Session = sessionmaker(bind=ENGINE, autocommit=False, autoflush=False) session = Session() user = User() user.name = "user1" user.password = "password" session.add(user) session.commit()
- 注意:session.commit() 是指事务提交,提交后无法回滚。session.flush() 也会写入数据库,但是可以执行 session.rollback() 回滚
1. 详细操作
1.1 建表
- 在 SQLAlchemy 中,以 ORM 方式定义表有两种方法,分别是 Classical 和 Declarative,Flask-Sqlalchemy主要使用的是 Declarative 方法:
from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() from sqlalchemy import Column, Integer, String def declarative_base(bind=None, metadata=None, mapper=None, cls=object, name='Base', constructor=_declarative_constructor, class_registry=None, metaclass=DeclarativeMeta): class _BoundDeclarativeMeta(DeclarativeMeta): def __init__(self, name, bases, d): bind_key = d.pop('__bind_key__', None) DeclarativeMeta.__init__(self, name, bases, d) if bind_key is not None: self.__table__.info['bind_key'] = bind_key def make_declarative_base(self, metadata=None): """Creates the declarative base.""" base = declarative_base(cls=Model, name='Model', metadata=metadata, metaclass=_BoundDeclarativeMeta) base.query = _QueryProperty(self) return base AdABCModelBase = make_declarative_base() class ABCAuth(AdABCModelBase): ''' ABC 授权 ''' __tablename__ = 'ABC_auth' __bind_key__ = 'ABC' __model_version__ = '2018-06-07' id = Column(BigInteger, primary_key=True) # ABCProductLibrary/ABCBehaviour id target_id = Column(BigInteger, default=0) type = Column(SmallInteger, default=0) av_id = Column(BigInteger, default=0) available = Column(Boolean, default=True) isdel = Column(Boolean, default=False) create_time = Column(DateTime) modify_time = Column(DateTime)
- declarative_base 的参数有:
- cls = Model
- metadata = metadata(None)
- metaclass = _BoundDeclarativeMeta
- _BoundDeclarativeMeta 是对 DeclarativeMeta 的一个简单包装
1.2 查询
- 通常通过 query 查询(详情见 SQLchemy 学习(一)Session 相关):
from sqlalchemy.orm import Session session = Session(engine) query = session.query(ABCAuth)
- 自定义对象查询:
query = ABCVideoPackage.query.filter(ABCVideoPackage.status != ABCVideoPackageStatus.DELETED)