SQLAlchemy
是Python最广泛使用的一个ORM(对象关系映射,简单地说就是把数据库的表即各种操作映射到Python对象上面来)工具。它支持操作
PostgreSQL
、
MySQL
、
Oracle
、
Microsoft SQL Server
、
SQLite
等支持SQL的数据库。
文档地址
需要特别注意的是,
SQLAlchemy
只是适用于一些通用的微型框架,而全栈框架
Django
的orm在结合特定框架用起来可能更加便利,所以在使用
SQLAlchemy
的时候,如果不知道怎么完成复杂的定义,那就干脆自己写sql吧,自己去join什么的
有另外一个选择
peewee
,提供类似Django那样又好的查询API,比
SQLAlchemy
易用,虽然可能没那么强大,性能可能也没那么好(并没有人去对比过性能),但是
peewee
还不支持
Oracle
等数据库,虽然我不用,但是为了防止以后多学习一门,就决定是
SQLAlchemy
了
SQLAlchemy
本身并不支持异步,在
tornado/sanic
中只有手动去执行异步
1 2 3 4 5 6 7 8 9 10 11 12
from sqlalchemy.ext.declarative import declarative_baseBase = declarative_base() class User (Base ): __tablename__ = 'users' __mapper_args__ = {'column_prerfix' : '_' } id = Column('user_id' , Integer, primary_key=True ) class __str__ (self ): return f'<{self.__class__.__module__} .{self.__class__.__name__} (id={self.id } )>' User.__table__.columns
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
BigInteger Boolean Enum Float SmallInteger Integer(unsigned=False ) Interval Numeric JSON LargeBinary(length=None ) PickleType SchemaType String(50 ) Text(length=None ) Unicode UnicodeText Date DateTime Time TIMESTAMP fullname = column_property(firstname + ' ' + lastname) primary_key=True comment='' table_name.column_name.name nullable=False