python 之 SQLALchemy
SQLALchemy
SQLAlchemy是Python编程语言下的一款ORM框架,该框架建立在数据库API之上,使用关系对象映射进行数据库操作,简言之便是:将对象转换成SQL,然后使用数据API执行SQL并获取执行结果。
ORM方法论基于三个核心原则:
简单:以最基本的形式建模数据。
传达性:数据库结构被任何人都能理解的语言文档化。
精确性:基于数据模型创建正确标准化了的结构。
Dialect用于和数据API进行交流,根据配置文件的不同调用不同的数据库API,从而实现对数据库的操作,如:
'数据库类型+数据库驱动名称://用户名:口令@机器地址:端口号/数据库名'
MySQL-Python
mysql+mysqldb://<user>:<password>@<host>[:<port>]/<dbname>
pymysql
mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]
MySQL-Connector
mysql+mysqlconnector://<user>:<password>@<host>[:<port>]/<dbname>
cx_Oracle
oracle+cx_oracle://user:pass@host:port/dbname[?key=value&key=value...]
http://docs.sqlalchemy.org/en/latest/orm/
PS
2.7版本使用mysqldb 3.5版本使用pymysql 请用pip或者源码包安装,确保环境可以正常使用。** 确保远程数据库服务器可以正常使用,并且拥有全新可以远程登录, 例如: 登录数据库:mysql -uroot -p 创建数据库:create database test; 授权库:grant all on test.* to root@"%" identified by '123'; 更新:flush privileges;
1.基本操作:
1)链接数据库:create_engine()
engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/test", max_overflow=5) create_engine() 会返回一个数据库引擎, mysql+pymysql” 指定了使用 MySQL-Python 来连接, 使用用户名‘root’ 和密码‘123’来链接数据库 121.42.195.15 是数据库链接地址可以是localhost,127.0.0.1 ‘test’ 是数据库名 max_overflow 是最大连接数 其他方法: “charset” 指定了连接时使用的字符集(可省略)=utf8 echo 参数为 True 时,会显示每条执行的 SQL 语句,生产环境下可关闭。
2)字段和数据类型及操作方法
在sqlalchemy.schema包里有数据库关系的描述,列举几个最常用的:
字段:Column
索引:Index
表:Table
数据类型在sqlalchemy.types包,列举几个最常用的:
二进制:BIGINT
布尔:BOOLEAN
字符:CHAR
可变字符:VARCHAR
日期:DATETIME
其他方法 execute,update,insert,select,delete,join等 自行补脑
3)创建表结构
使用 Schema Type/SQL Expression Language/Engine/ConnectionPooling/Dialect 进行数据库操作。Engine使用Schema Type创建一个特定的结构对象,之后通过SQL Expression Language将该对象转换成SQL语句,然后通过 ConnectionPooling 连接数据库,再然后通过 Dialect 执行SQL,并获取结果。
# /usr/bin/env python # -*- coding:utf8 -*- # auth rain from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData, ForeignKey import pymysql # 创建连接数据库 engin = create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/test", max_overflow=5) print(engin) # 获取元数据 metadata = MetaData() print(metadata) # 创建表 user = Table('user', metadata, Column('id', Integer, primary_key=True), Column('name', String(20)), ) color = Table('color', metadata, Column('id', Integer, primary_key=True), Column('name', String(20)), ) # 创建数据表,如果数据表存在,则忽视 metadata.create_all(engin) 结果: mysql> show tables; +------------------+ | Tables_in_liuyao | +------------------+ | color | | user | +------------------+ 2 rows in set (0.00 sec)
3)插入一条数据
使用 Engine/ConnectionPooling/Dialect 进行数据库操作,Engine使用ConnectionPooling连接数据库,然后再通过Dialect执行SQL语句。
#!/bin/bin/env python # -*-coding:utf-8 -*- # Author : rain from sqlalchemy import create_engine engine = create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/test", max_overflow=5) engine.execute("insert into test.color(id,name) VALUE ('1', 'rain')") engine.execute("insert into test.color(name) VALUE ('wind')") result = engine.execute('select * from color') print(result.fetchall()) # [(1, 'rain'), (2, 'wind')]
4) 增删改查
先创建数据库
from sqlalchemy import create_engine, Table, Column, Integer, String, ForeignKey, MetaData
engine = create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/test", max_overflow=5)
metadata = MetaData()
conn = engine.connect()
user = Table('user', metadata,
Column('id', Integer, primary_key=True),
Column('name', String(20)),
)
color = Table('color', metadata,
Column('id', Integer, primary_key=True),
Column('name', String(20)),
)
metadata.create_all(engine)
结果:
mysql> show tables;
+------------------+
| Tables_in_liuyao |
+------------------+
| color | | user |
+------------------+
2 rows in set (0.00 sec)
增加
# 创建SQL语句,INSERT INTO "user" (id, name) VALUES (:id, :name) # 插入一条数据(id为自动增加值可写,可不写) # sql = user.insert().values(id=1, name='yxy') sql = user.insert().values(name='yxy') conn.execute(sql) conn.close() mysql> select * from user; +----+------+ | id | name | +----+------+ | 1 | yxy | +----+------+ 1 row in set (0.00 sec)
删除
#删除一条user表里的 条件是id大于1的 sql = user.delete().where(user.c.id > 1) #执行 conn.execute(sql) #关闭链接 conn.close() 结果: mysql> select * from user; +----+------+ | id | name | +----+------+ | 1 | yxy | +----+------+ 1 row in set (0.00 sec)
修改/更新
from sqlalchemy import create_engine, Table, Column, Integer, String, ForeignKey, MetaData engine = create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/test", max_overflow=5) metadata = MetaData() conn = engine.connect() user = Table('user', metadata, Column('id', Integer, primary_key=True), Column('name', String(20)), ) color = Table('color', metadata, Column('id', Integer, primary_key=True), Column('name', String(20)), ) metadata.create_all(engine) for i in range(5): sql = user.insert().values(name='yxy %s' % i) conn.execute(sql) conn.close() mysql> select * from user; +----+-------+ | id | name | +----+-------+ | 1 | yxy | | 8 | yxy 0 | | 9 | yxy 1 | | 10 | yxy 2 | | 11 | yxy 3 | | 12 | yxy 4 | +----+-------+ 6 rows in set (0.00 sec)
# 数据库原始记录为如下 : mysql> select * from user; +----+-------+ | id | name | +----+-------+ | 1 | yxy | | 8 | yxy 0 | | 9 | yxy 1 | | 10 | yxy 2 | | 11 | yxy 3 | | 12 | yxy 4 | +----+-------+ 6 rows in set (0.00 sec)
#更新 #把名字为yxy的修改为change_name sql = user.update().where(user.c.name == 'yxy').values(name='change_name') conn.execute(sql) conn.close() 结果: mysql> select * from user; +----+-------------+ | id | name | +----+-------------+ | 1 | change_name | | 8 | yxy 0 | | 9 | yxy 1 | | 10 | yxy 2 | | 11 | yxy 3 | | 12 | yxy 4 | +----+-------------+ 6 rows in set (0.00 sec)
查询
注:请导入查询模块
#!/bin/bin/env python # -*-coding:utf-8 -*- # Author : rain from sqlalchemy import select from sqlalchemy import create_engine, Table, Column, Integer, String, ForeignKey, MetaData engine = create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/test", max_overflow=5) metadata = MetaData() conn = engine.connect() metadata.create_all(engine) user = Table('user', metadata, Column('id', Integer, primary_key=True), Column('name', String(20)), ) color = Table('color', metadata, Column('id', Integer, primary_key=True), Column('name', String(20)), ) metadata.create_all(engine) # 查询user表里的内容 sql = select([user]) res = conn.execute(sql) print(res.fetchall()) # [(1, 'change_name'), (8, 'yxy 0'), (9, 'yxy 1'), (10, 'yxy 2'), (11, 'yxy 3'), (12, 'yxy 4')] # 查询user表下的id sqlid = select([user.c.id]) rest = conn.execute(sqlid) print(rest.fetchall()) # [(1,), (8,), (9,), (10,), (11,), (12,)] # 查询user表和color表的name,条件是user表的id1=color的id1 sqltwo = select([user.c.name, color.c.name]).where(user.c.id == color.c.id) restwo = conn.execute(sqltwo) print(restwo.fetchall()) # [('change_name', 'rain')] # 查询user表的name,并按照条件排序,按照名字排序 sqlorder = select([user.c.name]).order_by(user.c.name) resorder = conn.execute(sqlorder) print(resorder.fetchall()) # [('change_name',), ('yxy 0',), ('yxy 1',), ('yxy 2',), ('yxy 3',), ('yxy 4',)] # 按照id排序 sqlorderid = select([user.c.name]).order_by(user.c.id) resorderid = conn.execute(sqlorderid) print(resorderid.fetchall()) # [('change_name',), ('yxy 0',), ('yxy 1',), ('yxy 2',), ('yxy 3',), ('yxy 4',)] # 查询user表的name,并按照条件分组 sqlgroup = select([user]).group_by(user.c.name) resgroup = conn.execute(sqlgroup) print(resgroup.fetchall()) # [(1, 'change_name'), (8, 'yxy 0'), (9, 'yxy 1'), (10, 'yxy 2'), (11, 'yxy 3'), (12, 'yxy 4')] # 按照id sqlgroupid = select([user]).group_by(user.c.name) resgroupid = conn.execute(sqlgroupid) print(resgroupid.fetchall()) # [(1, 'change_name'), (8, 'yxy 0'), (9, 'yxy 1'), (10, 'yxy 2'), (11, 'yxy 3'), (12, 'yxy 4')] conn.close()
5)继承SqlORM类来操作数据库
# /usr/bin/env python # -*- coding:utf8 -*- # auth rain from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String from sqlalchemy.orm import sessionmaker # 生成一个SqlORM 基类 Base = declarative_base() # echo如果为True,那么当他执行整个代码的数据库的时候会显示过程 engine = create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/test", echo=True) # 创建一个类继承Base基类 class Host(Base): # 表名为hosts __tablename__ = 'host' # 表结构 # primary_key等于主键 # unique唯一 # nullable非空 id = Column(Integer,primary_key=True, autoincrement=True) hostname = Column(String(64), unique=True, nullable=False) ip_addr = Column(String(128), unique=True, nullable=False) port = Column(Integer, default=22) # 创建所有表结构 Base.metadata.create_all(engine) if __name__ == '__main__': # bind绑定 # 创建与数据库的会话session class SessionCls = sessionmaker(bind=engine) # 注意,这里返回给session的是个class,不是实例 session = SessionCls() # 插入字段 h1 = Host(hostname='app', ip_addr='10.10.33.100', port=22) h2 = Host(hostname='pymysql', ip_addr='10.10.33.111', port=80) h3 = Host(hostname='app2', ip_addr='10.10.33.222', port=8080) # 添加一个 session.add(h1) # 可以添加多个字段 session.add_all([h2, h3]) # 修改字段名字,只要没提交,此时修改也没问题 # h2.hostname = 'ubuntu_test' # 支持数据回滚 # session.rollback() # 提交 session.commit()
mysql> select * from host; +----+----------+--------------+------+ | id | hostname | ip_addr | port | +----+----------+--------------+------+ | 1 | app | 10.10.33.100 | 22 | | 5 | pymysql | 10.10.33.111 | 80 | | 6 | app2 | 10.10.33.222 | 8080 | +----+----------+--------------+------+ 3 rows in set (0.00 sec)
注:SQLAlchemy无法修改表结构,如果需要可以使用SQLAlchemy开发者开源的另外一个软件Alembic来完成。
6.继承类式增删改查:
使用 ORM/Schema Type/SQL Expression Language/Engine/ConnectionPooling/Dialect 所有组件对数据进行操作。根据类创建对象,对象转换成SQL,执行SQL。
Query对象可以返回可迭代的值(iterator value),然后我们可以通过for in来查询。不过Query对象的all()、one()以及first()方法将返回非迭代值(non-iterator value),比如说all()返回的是一个列表first()方法限制并仅作为标量返回结果集的第一条记录:
1)先创建相关数据库
#!/usr/bin/env python # -*- coding:utf-8 -*- from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine #创建数据库 engine = create_engine("mysql+mysqldb://root:123456@121.42.195.15:3306/test", max_overflow=5) #生成一个SqlORM 基类 Base = declarative_base() #定义表结构 class User(Base): #表名 __tablename__ = 'users' #定义id,主键唯一, id = Column(Integer, primary_key=True) name = Column(String(50)) #寻找Base的所有子类,按照子类的结构在数据库中生成对应的数据表信息 Base.metadata.create_all(engine) #创建与数据库的会话session class ,注意,这里返回给session的是个class,不是实例 Session = sessionmaker(bind=engine) session = Session() #获取session,然后把对象添加到session, #最后提交并关闭。Session对象可视为当前数据库连接。
2.增加
########### 增 ########## #定义一个字段 zengjia = User(id=2, name='sbliuyao') #添加字段 session.add(zengjia) #添加多个字段 session.add_all([ User(id=3, name='sbyao'), User(id=4, name='liuyao') ]) #提交以上操作 session.commit() 结果: mysql> select * from users; +----+----------+ | id | name | +----+----------+ | 2 | sbliuyao | | 3 | sbyao | | 4 | liuyao | +----+----------+ 3 rows in set (0.00 sec)
3.删除
# ########## 删除 ########## #删除user表,id大于2的字段 session.query(User).filter(User.id > 2).delete() session.commit() 结果: mysql> select * from users; +----+----------+ | id | name | +----+----------+ | 2 | sbliuyao | +----+----------+ 1 row in set (0.00 sec)
4.修改
因上次操作已经删除好多数据 请重新执行插入字段操作 session.add_all([ User(id=3, name='sbyao'), User(id=4, name='liuyao'), User(id=5, name='mayun') ]) session.commit() 结果: mysql> select * from users; +----+----------+ | id | name | +----+----------+ | 2 | sbliuyao | | 3 | sbyao | | 4 | liuyao | | 5 | mayun | +----+----------+ 4 rows in set (0.00 sec) 在执行以下操作 #user表里的id等于2的字段修改为id=6 session.query(User).filter(User.id == 2).update({'id' : 6}) session.commit() 结果: mysql> select * from users; +----+----------+ | id | name | +----+----------+ | 3 | sbyao | | 4 | liuyao | | 5 | mayun | | 6 | sbliuyao | +----+----------+ 4 rows in set (0.00 sec) 其他方法: #把user表里id大于2的name全部换成woshiyaoge session.query(User).filter(User.id > 2).update({'name' :'woshiyaoge'}) session.commit() mysql> select * from users; +----+------------+ | id | name | +----+------------+ | 3 | woshiyaoge | | 4 | woshiyaoge | | 5 | woshiyaoge | | 6 | woshiyaoge | +----+------------+ 4 rows in set (0.00 sec)
5.查询
数据库如下: mysql> select * from users; +----+------------+ | id | name | +----+------------+ | 3 | woshiyaoge | | 4 | woshiyaoge | | 5 | woshiyaoge | | 6 | woshiyaoge | | 7 | sbyao | | 8 | liuyao | | 9 | mayun | +----+------------+ 7 rows in set (0.00 sec) 方式1: #查询user表下面name=liuyao的字段 ret = session.query(User).filter_by(name='liuyao').all() #打印实例 print ret for i in ret: #打印结果 print(i.id,i.name,) 结果: [<__main__.User object at 0x0000000002F55860>] (8L, 'liuyao') 这种查询方法可以返回一个User对象以及它的name属性字段的值。 方式2: #查询user表里字段是name=liuyao的第一条数据 ret = session.query(User).filter_by(name='liuyao').first() print ret.name print ret.id 结果: liuyao 8 方式3: #查询user表里字段是name是liuyao或者mayun的信息打印出来 ret = session.query(User).filter(User.name.in_(['liuyao','mayun'])).all() print ret for i in ret: print(i.name,i.id) 结果: [<__main__.User object at 0x00000000030F1E48>, <__main__.User object at 0x000000000311D8D0>] ('liuyao', 8L) ('mayun', 9L) 方式4: #可以给返回的结果起一个别名,或者叫标签:可有可无 ret = session.query(User.name.label('')).all() print ret,type(ret) 这里的关键是label方法,它的意思是把User的name字段改个名字叫name_label, 其相当于执行以下的SQL语句: SELECT users.name AS name_label FROM users 结果: [('woshiyaoge',), ('woshiyaoge',), ('woshiyaoge',), ('woshiyaoge',), ('sbyao',), ('liuyao',), ('mayun',)] <type 'list'> 方式5: #查询User表根据id排序 ret = session.query(User).order_by(User.id).all() print ret for i in ret: print(i.name) 结果: [<__main__.User object at 0x00000000031978D0>, <__main__.User object at 0x0000000003197978>, <__main__.User object at 0x00000000031979E8>, <__main__.User object at 0x0000000003197A58>, <__main__.User object at 0x000000000316BE10>, <__main__.User object at 0x000000000316BE48>, <__main__.User object at 0x0000000003197940>] woshiyaoge woshiyaoge woshiyaoge woshiyaoge sbyao liuyao mayun 方式6: #查询user表里根据id排序输入0到3的字段 ret = session.query(User).order_by(User.id)[0:3] print ret for i in ret: print(i.name) 结果: [<__main__.User object at 0x00000000030F59E8>, <__main__.User object at 0x00000000030C9E80>, <__main__.User object at 0x00000000030C9C88>] woshiyaoge woshiyaoge woshiyaoge 方式7: # 创建Query查询,filter是where条件,最后调用one()返回唯一行,如果调用all()则返回所有行: user = session.query(User).filter(User.id=='5').one() #打印类型和对象的name属性: print 'type:', type(user) print 'name:', user.name
7.外键关联
由于关系数据库的多个表还可以用外键实现一对多、多对多等关联,相应地,ORM框架也可以提供两个对象之间的一对多、多对多等功能。
1)一对多(一个User可以有多个Address)
外键引用relationship()
例: #!/usr/bin/env python3 #coding:utf8 #导入所需模块 from sqlalchemy import create_engine,func from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String,ForeignKey from sqlalchemy.orm import sessionmaker,relationship #生成sqlorm基类 Base = declarative_base() #创建数据库连接 engine = create_engine("mysql+mysqldb://root:123456@121.42.195.15:3306/test", max_overflow=5) #目的是一个人可以拥有多本书,那么在数据库里的一对多关系 class User(Base): #表名 __tablename__ = 'user' #id字段 id = Column(String(20), primary_key=True) #名字字段 name = Column(String(20)) # 一对多:#内容不是表名而是定义的表结构名字 books = relationship('Book') class Book(Base): #表面 __tablename__ = 'book' #id字段 id = Column(String(20), primary_key=True) #名字字段 name = Column(String(20)) # “多”的一方的book表是通过外键关联到user表的: #ForeignKey是外键 关联user表的id字段 user_id = Column(String(20), ForeignKey('user.id')) #创建所需表 Base.metadata.create_all(engine) if __name__ == '__main__': #绑定,生成回话 SessionCls = sessionmaker(bind=engine) session = SessionCls() #创建用户 liuyao = User(id='1',name='liuyao') ali=User(id='2',name='ali') #添加字段 session.add_all([liuyao,ali]) #提交 session.commit() #创建白鹿原这本书,指定谁是拥有者 Whitedeer = Book(id='1',name='White_deer',user_id = '1') #创建三体这本书,指定谁是拥有者 Threebody = Book(id='2',name='Three_body',user_id = '2') #添加字段 session.add_all([Whitedeer,Threebody]) #提交 session.commit() 结果: 表: mysql> show tables; +------------------+ | Tables_in_liuyao | +------------------+ | book | | user | +------------------+ rows in set (0.00 sec) user表: mysql> select * from user; +----+--------+ | id | name | +----+--------+ | 1 | liuyao | | 2 | ali | +----+--------+ 2 rows in set (0.00 sec) book表#已经显示关联哪个user表id mysql> select * from book; +----+------------+---------+ | id | name | user_id | +----+------------+---------+ | 1 | White_deer | 1 | | 2 | Three_body | 2 | +----+------------+---------+ 2 rows in set (0.00 sec)
2)多对多
建立一个双向一对多关系,“反向”是一个许多人,指定一个额外的relationship()函数
并连接两个使用relationship.back_populates参数
简单来说, relationship函数是sqlalchemy对关系之间提供的一种便利的调用方式, backref参数则对关系提供反向引用的声明。在最新版本的sqlalchemy中对relationship引进了back_populates参数。
先创建数据库:
#!/usr/bin/env python3 #coding:utf8 from sqlalchemy import Column, Sequence, String, Integer, ForeignKey from sqlalchemy import create_engine # 导入创建连接驱动 from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import relationship, backref # 这个url可以用urlparse解析, 其中echo=True表示执行时显示sql语句
engine = create_engine("mysql+mysqldb://root:123456@121.42.195.15:3306/test", max_overflow=5)
#生成了declarative基类, 以后的model继承此类 Base = declarative_base() class Parent(Base): __tablename__ = 'parent' id = Column(Integer, primary_key=True) name = Column(String(64),unique=True,nullable=False) children = relationship("Child", back_populates="parent") class Child(Base): __tablename__ = 'child' id = Column(Integer, primary_key=True) name = Column(String(64),unique=True,nullable=False) parent_id = Column(Integer, ForeignKey('parent.id')) parent = relationship("Parent", back_populates="children") Base.metadata.create_all(engine) #创建所有表结构 if __name__ == '__main__': SessionCls = sessionmaker(bind=engine) #创建与数据库的会话session class ,注意,这里返回给session的是个class,不是实例 session = SessionCls() mama = Parent(id='1',name='mamaxx') baba = Parent(id='2',name='babaoo') session.add_all([mama,baba]) # onesb = Child(id='1',name='onesb',parent_id='2') # twosb = Child(id='2',name='twosb',parent_id='2') #session.add_all([onesb,twosb]) session.commit()
3.)多对多之三表外键关联
#!/usr/bin/env python3 #coding:utf8 from sqlalchemy import create_engine,func,Table from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String,ForeignKey from sqlalchemy.orm import sessionmaker,relationship Base = declarative_base() #关系表 Host2Group = Table('host_2_group',Base.metadata, Column('host_id',ForeignKey('hosts.id'),primary_key=True), Column('group_id',ForeignKey('group.id'),primary_key=True), )
#!/usr/bin/env python3
#coding:utf8
from sqlalchemy import create_engine,func,Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String,ForeignKey
from sqlalchemy.orm import sessionmaker,relationship
Base = declarative_base()
#关系表
Host2Group = Table('host_2_group',Base.metadata,
Column('host_id',ForeignKey('hosts.id'),primary_key=True),
Column('group_id',ForeignKey('group.id'),primary_key=True),
)
engine = create_engine("mysql+mysqldb://liuyao:liuyao@121.42.195.15:3306/liuyao", max_overflow=5)
class Host(Base):
__tablename__ = 'hosts'
id = Column(Integer,primary_key=True,autoincrement=True)
hostname = Column(String(64),unique=True,nullable=False)
ip_addr = Column(String(128),unique=True,nullable=False)
port = Column(Integer,default=22)
groups = relationship('Group',
secondary= Host2Group,
backref = 'host_list')
class Group(Base):
__tablename__ = 'group'
id = Column(Integer,primary_key=True)
name = Column(String(64),unique=True,nullable=False)
if __name__ == '__main__':
SessionCls = sessionmaker(bind=engine)
session = SessionCls()
g1 = Group(name='g1')
g2 = Group(name='g2')
g3 = Group(name='g3')
g4 = Group(name='g4')
session.add_all([g1,g2,g3,g4])
session.commit()
class Host(Base): __tablename__ = 'hosts' id = Column(Integer,primary_key=True,autoincrement=True) hostname = Column(String(64),unique=True,nullable=False) ip_addr = Column(String(128),unique=True,nullable=False) port = Column(Integer,default=22) groups = relationship('Group', secondary= Host2Group, backref = 'host_list') class Group(Base): __tablename__ = 'group' id = Column(Integer,primary_key=True) name = Column(String(64),unique=True,nullable=False) if __name__ == '__main__': SessionCls = sessionmaker(bind=engine) session = SessionCls() g1 = Group(name='g1') g2 = Group(name='g2') g3 = Group(name='g3') g4 = Group(name='g4') session.add_all([g1,g2,g3,g4]) session.commit()
参考博文: http://www.cnblogs.com/liu-yao/p/5342656.html