在对表对象进行创建的时候,一般有两种方式能够完成,如下是两种方式的创建过程对比sql
首先导入须要的模块,获取一个声明层api
1 from sqlalchemy.sql.schema import Table, Column 2 from sqlalchemy.sql.sqltypes import Integer 3 from sqlalchemy.ext.declarative import declarative_base 4 5 Base = declarative_base()
两种方法,spa
Note: 此处两种方法都使用声明层做为基类,第一种方法未传入metadata,会自动使用Base.metadata,第二种方法则直接进行了传入。code
1 # Method one: 2 class table_one(Base): 3 __tablename__ = 'table_one' 4 id = Column(Integer, primary_key=True) 5 6 # Method two: 7 class table_two(Base): 8 __table__ = Table('table_two', Base.metadata, 9 Column('id', Integer, primary_key=True))
最后运行显示orm
1 print(type(table_one), type(table_one.id), table_one.id, sep='\n') 2 print(type(table_two), type(table_two.id), table_two.id, sep='\n')
输出结果对象
<class 'sqlalchemy.ext.declarative.api.DeclarativeMeta'> <class 'sqlalchemy.orm.attributes.InstrumentedAttribute'> table_one.id <class 'sqlalchemy.ext.declarative.api.DeclarativeMeta'> <class 'sqlalchemy.orm.attributes.InstrumentedAttribute'> table_two.id
从输出的结果中能够看出,两种方式创建的表是相同类型的。blog