码迷,mamicode.com
首页 > 数据库 > 详细

sqlalchemy进阶

时间:2016-08-05 10:02:42      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

ORM的创建方式

•数据库优先:先创建数据库,然后根据数据库生成ORM的代码

•代码优先:根据代码去生成数据库结构

Sqlalchemy操作

•一个组对应多个表

# 表结构<br>class Group(Base): # 一对多的表,组中可能包含多个用户
    __tablename__ = group
    nid = Column(Integer, primary_key=True, autoincrement=True)
    caption = Column(String(32))
 
class User(Base):
    __tablename__ = user
    uid = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(32))
    gid = Column(Integer, ForeignKey(group.nid))

# 创建完表之后,建立连接
Session = sessionmaker(bind=engine)
session = Session()

新增Group表数据
session.add_all([
    Group(caption=DBA),
    Group(caption=SA),
    ]
)
session.commit()
session.add(Group(caption=QA))
新建User表数据
session.add_all([
    User(name=Bob, gid=1),
    User(name=Boss, gid=2),
    ]
)
session.commit()

•多对多关系

class Host(Base):
    __tablename__ = host
    nid = Column(Integer, primary_key=True, autoincrement=True)
    hostname = Column(String(32))
    port = Column(String(32))
    ip = Column(String(32))
 
class HostUser(Base):
    __tablename__ = host_user
    nid = Column(Integer, primary_key=True, autoincrement=True)
    username = Column(String(32))
 
# 多对多
class HostToHostUser(Base):
    __tablename__ = host_to_host_user
    nid = Column(Integer, primary_key=True, autoincrement=True)
 
    # 两个关联的id,以外键的形式存在
    host_id = Column(Integer, ForeignKey(host.nid))
    host_user_id = Column(Integer, ForeignKey(host_user.nid))

# 创建完表之后,建立连接
Session = sessionmaker(bind=engine)
session = Session()
# 新增表数据
session.add_all([
    Host(hostname=c1,port=22,ip=1.1.1.1),
    Host(hostname=c2,port=22,ip=1.1.1.2),
    Host(hostname=c3,port=22,ip=1.1.1.3),
    Host(hostname=c4,port=22,ip=1.1.1.4),
    Host(hostname=c5,port=22,ip=1.1.1.5),
])
session.commit()

session.add_all([
    HostUser(username=root),
    HostUser(username=alex),
    HostUser(username=eric),
    HostUser(username=bob),
])
session.commit()

session.add_all([
    HostToHostUser(host_id=1,host_user_id=1),
    HostToHostUser(host_id=1,host_user_id=2),
    HostToHostUser(host_id=2,host_user_id=3),
    HostToHostUser(host_id=2,host_user_id=2),
    HostToHostUser(host_id=3,host_user_id=4),
    HostToHostUser(host_id=3,host_user_id=3),
])
session.commit()

 

sqlalchemy进阶

标签:

原文地址:http://www.cnblogs.com/pangzhi/p/5740078.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!