sqlalchemy一些常见概念

metadata

官方文档解释

The MetaData is a registry which includes the ability to emit a limited set of schema generation commands to the database. As our SQLite database does not actually have a users table present, we can use MetaData to issue CREATE TABLE statements to the database for all tables that don’t yet exist. Below, we call the MetaData.create_all() method, passing in our Engine as a source of database connectivity

metadata是一个注册器,里面包含一些数据库的模式生成命令,可以调用metadata发起create table命令来创建这个表

image_1cdjqt91j1hpr34cos1euqodr9.png-5.9kB


mapper

sqlalchemy中创建一个继承declarative_base的类的本质是,创建一个class的同时生成一个同名的Table对象,并且使用一个mapper对象将两个对象映射在一起。

1
2
3
4
5
6
7
8
9
class MyClass(Base):
__tablename__ = 'my_table'
id = Column(Integer, primary_key=True)
type = Column(String(50))
alt = Column("some_alt", Integer)

__mapper_args__ = {
'polymorphic_on' : type
}

上述代码跟下面效果是一样的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
my_table = Table("my_table", metadata,
Column('id', Integer, primary_key=True),
Column('type', String(50)),
Column("some_alt", Integer)
)

class MyClass(object):
pass

mapper(MyClass, my_table,
polymorphic_on=my_table.c.type,
properties={
'alt':my_table.c.some_alt
})


对象状态转换

image_1cdjs8hm616i15k3vss1r6u17ju3j.png-14.2kB

值得一提的是,当class被add到session中,但是没有commit,此时这个class并没有被写入数据库,但是此时进行query查询这个class是可以被查询出来的,因为当执行query时,执行了flush操作,调用了sql语句,这个class对应的row被生成。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from sqlalchemy import Column, String, Integer, ForeignKey, create_engine
from sqlalchemy.orm import sessionmaker, relationship, backref
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = "user"
id = Column(Integer, primary_key = True)
name = Column(String(20))

engine = create_engine('mysql+mysqlconnector://root:Gzm20125@localhost:3306/test')
DBSession = sessionmaker(bind = engine)

Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)
# 创建session对象:

session = DBSession()

u = User(id = 1, name = "gzm")
session.add(u)
print(session.query(User).filter_by(id = 1).first())

输出
image_1cdjsg49k1qk49j6192o1vmd1vdp40.png-13.5kB