day13 SQLAlchemy

Posted valiente

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了day13 SQLAlchemy相关的知识,希望对你有一定的参考价值。

ORM:也叫关系对象映射

本篇要点:

  • 原生模块 pymsql
  • ORM框架 SQLAchemy

pymysql

pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同。

需要准备的环境:

pymysql的使用操作:

  • 执行SQL语句:

SQLAchemy

  

SQLAlchemy本身无法操作数据库,其必须以来pymsql等第三方插件,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/dialects/index.html
  • 创建表:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,Integer,String,ForeignKey,UniqueConstraint,Index
from sqlalchemy.orm import sessionmaker,relationship
from sqlalchemy import create_engine

engine = create_engine("mysql+pymysql://root:123456@10.70.18.100:3306/ttt",max_overflow=5)    #连接数据库
Base = declarative_base()
#创建单表:
class Users(Base):     #类必须要继承Base
    __tablename__ = \'users\'     #表名
    id = Column(Integer,primary_key=True)    #创建列
    name = Column(String(32))
    extra = Column(String(16))
    __table_args__ = (
        UniqueConstraint(\'id\',\'name\',name=\'centos\'),     #联合索引
        Index(\'ix_id_name\',\'name\',\'extra\'),
    )

#一对多
class Favor(Base):
    __tablename__ = \'favor\'
    nid = Column(Integer,primary_key=True)
    caption = Column(String(50),default=\'red\',unique=True)
class Person(Base):
    __tablename__ = \'person\'
    nid = Column(Integer,primary_key=True)
    name = Column(String(32),index=True,nullable=True)
    favor_id = Column(Integer,ForeignKey("favor.nid"))     #根上一个favor的nid做外键
#多对多
class ServerToGroup(Base):
    __tablename__ = \'servertogroup\'
    id = Column(Integer,primary_key=True,autoincrement=True)
    hostname = Column(String(64),unique=True,nullable=False)

class Group(Base):
    __tablename__ = \'group\'
    id = Column(Integer,primary_key=True)
    name = Column(String(64),unique=True,nullable=False)

class Server(Base):
    __tablename__ = \'server\'
    id = Column(Integer,primary_key=True,autoincrement=True)
    hostname = Column(String(64),unique=True,nullable=False)
    port = Column(Integer,default=22)

# def init_db():
#     Base.metadata.create_all(engine)
# init_db()    #创建

def drop_db():
    Base.metadata.drop_all(engine)

drop_db()    #删除
  • 表操作(增删改查)

1.增加操作

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,Integer,String,ForeignKey,UniqueConstraint,Index
from sqlalchemy.orm import sessionmaker,relationship
from sqlalchemy import create_engine

engine = create_engine("mysql+pymysql://root:123456@10.70.18.100:3306/ttt",max_overflow=5,encoding=\'utf-8\', echo=True)    #连接数据库
Base = declarative_base()
#创建单表:
class Users(Base):     #类必须要继承Base
    __tablename__ = \'users\'     #表名
    id = Column(Integer,primary_key=True,autoincrement=True)    #创建列
    name = Column(String(32))
    extra = Column(String(16))
    __table_args__ = (
        UniqueConstraint(\'id\',\'name\',name=\'centos\'),     #联合索引
        Index(\'ix_id_name\',\'name\',\'extra\'),
    )
def init_db():                                 # 首先要创建单表
    Base.metadata.create_all(engine)
init_db()                                        #初始化表

Session = sessionmaker(bind=engine)           #会话绑定
session = Session()

obj = Users(name=\'wanghui\',extra=\'ssss\')    #单条数据操作
session.add(obj)                              #增加单条数据
session.add_all([                             #多条数据的增加
    Users(name=\'xyz\',extra=\'wsss\'),
    Users(name=\'sssd\',extra=\'dadsad\'),
    Users(name=\'jack\',extra=\'hello\'),
    Users(name=\'jack1\',extra=\'hello\'),
    Users(name=\'jack2\',extra=\'hello\'),
    Users(name=\'jack3\',extra=\'hello\')
])
session.commit()                              #提交

2.删除操作

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,Integer,String,ForeignKey,UniqueConstraint,Index
from sqlalchemy.orm import sessionmaker,relationship
from sqlalchemy import create_engine

engine = create_engine("mysql+pymysql://root:123456@10.70.18.100:3306/ttt",max_overflow=5,encoding=\'utf-8\', echo=True)    #连接数据库
Base = declarative_base()
#创建单表:
class Users(Base):     #类必须要继承Base
    __tablename__ = \'users\'     #表名
    id = Column(Integer,primary_key=True)    #创建列
    name = Column(String(32))
    extra = Column(String(16))
    __table_args__ = (
        UniqueConstraint(\'id\',\'name\',name=\'centos\'),     #联合索引
        Index(\'ix_id_name\',\'name\',\'extra\'),
    )
# def init_db():                                 # 首先要创建单表
#     Base.metadata.create_all(engine)
# init_db()                                        #初始化表

Session = sessionmaker(bind=engine)           #会话绑定
session = Session()
session.query(Users).filter(Users.id > 2).delete()      #删除的话也是根据条件进行伤处操作的
session.commit()

3.修改操作

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,Integer,String,ForeignKey,UniqueConstraint,Index
from sqlalchemy.orm import sessionmaker,relationship
from sqlalchemy import create_engine

engine = create_engine("mysql+pymysql://root:123456@10.70.18.100:3306/ttt",max_overflow=5,encoding=\'utf-8\', echo=True)    #连接数据库
Base = declarative_base()
#创建单表:
class Users(Base):     #类必须要继承Base
    __tablename__ = \'users\'     #表名
    id = Column(Integer,primary_key=True)    #创建列
    name = Column(String(32))
    extra = Column(String(16))
    __table_args__ = (
        UniqueConstraint(\'id\',\'name\',name=\'centos\'),     #联合索引
        Index(\'ix_id_name\',\'name\',\'extra\'),
    )
# def init_db():                                 # 首先要创建单表
#     Base.metadata.create_all(engine)
# init_db()                                        #初始化表

Session = sessionmaker(bind=engine)           #会话绑定
session = Session()
session.query(Users).filter(Users.id > 2 ).update({\'name\':\'099\'})
session.query(Users).filter(Users.id > 2).update({Users.name:Users.name + \'099\'},synchronize_session = False)
session.commit()

4.查找操作

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,Integer,String,ForeignKey,UniqueConstraint,Index
from sqlalchemy.orm import sessionmaker,relationship
from sqlalchemy import create_engine

engine = create_engine("mysql+pymysql://root:123456@10.70.18.100:3306/ttt",max_overflow=5,encoding=\'utf-8\', echo=True)    #连接数据库
Base = declarative_base()
#创建单表:
class Users(Base):     #类必须要继承Base
    __tablename__ = \'users\'     #表名
    id = Column(Integer,primary_key=True)    #创建列
    name = Column(String(32))
    extra = Column(String(16))
    __table_args__ = (
        UniqueConstraint(\'id\',\'name\',name=\'centos\'),     #联合索引
        Index(\'ix_id_name\',\'name\',\'extra\'),
    )
# def init_db():                                 # 首先要创建单表
#     Base.metadata.create_all(engine)
# init_db()                                        #初始化表

Session = sessionmaker(bind=engine)           #会话绑定
session = Session()
ret1=session.query(Users).all()    #查询全部
ret2=session.query(Users.name,Users.extra).all()
ret3=session.query(Users).filter_by(name=\'099099\').all() #条件匹配查
ret4=session.query(Users).filter_by(name=\'099099\').first()
print(ret1[0].name,ret1[0].id,ret1[0].extra)      #获取第一行数据
print(ret1[1].name,ret1[1].id,ret1[1].extra)      #获取第二行的数据

5.其他操作

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,Integer,String,ForeignKey,UniqueConstraint,Index
from sqlalchemy.orm import sessionmaker,relationship
from sqlalchemy import create_engine
from sqlalchemy import all_,and_,or_,not_   #导入条件判断语句

engine = create_engine("mysql+pymysql://root:123456@10.70.18.100:3306/ttt",max_overflow=5,encoding=\'utf-8\', echo=True)    #连接数据库
Base = declarative_base()
#创建单表:
class Users(Base):     #类必须要继承Base
    __tablename__ = \'users\'     #表名
    id = Column(Integer,primary_key=True)    #创建列
    name = Column(String(32))
    extra = Column(String(16))
    __table_args__ = (
        UniqueConstraint(\'id\',\'name\',name=\'centos\'),     #联合索引
        Index(\'ix_id_name\',\'name\',\'extra\'),
    )
# def init_db():                                 # 首先要创建单表
#     Base.metadata.create_all(engine)
# init_db()                                        #初始化表

Session = sessionmaker(bind=engine)           #会话绑定
session = Session()

#条件
ret = session.query(Users).filter_by(name=\'wanghui\').all()    #条件过滤   (单个条件可以用filter_by)
#print(ret[0].name,ret[0].id,ret[0].extra)      #打印查查找的数据信息
res = session.query(Users).filter_by(name=\'wanghui\')
print(res)     #打印操作的SQL语句
ret1 = session.query(Users).filter(Users.id > 1 , Users.name == \'wanghui\').all()    #匹配查询(多个条件就不用filter_by了)
#print(ret[0].name,ret[0].id,ret[0].extra)
ret2=session.query(Users).filter(Users.id.between(1,35),Users.name==\'wanghui\').all()   #条件查询
ret3=session.query(Users).filter(Users.id.in_([1,34,40])).all()
ret4=session.query(Users).filter(~Users.id.in_([1,34,40])).all()     #非操作
ret5=session.query(Users).filter(and_(Users.id > 3,Users.name==\'wanghui\')).all()   #与操作
ret6=session.query(Users).filter(or_(Users.id > 3,Users.name==\'wanghui\')).all()    #或操作
ret7=session.query(Users).filter(
    or_(
        Users.id > 2,
        and_(Users.name == \'wanghui\',Users.id > 10),
        Users.extra != \'\'
    )).all()
#通配符
ret8 = session.query(Users).filter(Users.name.like(\'e%\')).all()     #模糊匹配
ret9 = session.query(Users).filter(~Users.name.like(\'e%\')).all()     #模糊匹配
#限制
ret10 = session.query(Users).filter(Users.id)[1:2]
#排序
ret11 = session.query(Users).order_by(Users.extra.desc()).all()     #desc表示逆序,asc表示顺序
ret12=session.query(Users).order_by(Users.name.desc(),Users.id.asc()).all()
#分组
from sqlalchemy.sql import func
ret13 = session.query(Users).group_by(Users.extra).all()
ret14 = session.query(
    func.max(Users.id),
    func.sum(Users.id),
    func.min(Users.id)).group_by(Users.name).having(func.min(Users.id) > 2).all()
#连表操作
ret = session.query(Users, Favor).filter(Users.id == Favor.nid).all()
ret = session.query(Person).join(Favor).all()
ret = session.query(Person).join(Favor, isouter=True).all()
# 组合
q1 = session.query(Users.name).filter(Users.id > 2)
q2 = session.query(Favor.caption).filter(Favor.nid < 2)
ret = q1.union(q2).all()
q1 = session.query(Users.name).filter(Users.id > 2)
q2 = session.query(Favor.caption).filter(Favor.nid < 2)
ret = q1.union_all(q2).all()

连表操作:

为什么要分表:

解决数据冗余的问题

约束问题:外键

单表查询:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,Integer,String,ForeignKey,UniqueConstraint,Index
from sqlalchemy.orm import sessionmaker,relationship

engine = create_engine("mysql+pymysql://root:123456@10.70.18.100:3306/zzz",max_overflow=5,encoding=\'utf-8\')    #连接数据库
# engine = create_engine("mysql+pymysql://root:123456@10.70.18.100:3306/zzz",max_overflow=5,encoding=\'utf-8\', echo=True)    #连接数据库
Base = declarative_base()
#建表
class Test(Base):
    __tablename__=\'test\'
    nid=Column(Integer,primary_key=True,autoincrement=True)
    name=Column(String(32))

#一对多表
class Group(Base):
    __tablename__=\'group\'
    nid=Column(Integer,primary_key=True,autoincrement=True)
    caption=Column(String(32))

class User(Base):
    __tablename__=\'user\'
    nid=Column(Integer,primary_key=True,autoincrement=True)
    username=Column(String(32))
    group_id=Column(Integer,ForeignKey(Group.nid))     #和group的id建立关系
    def __repr__(self):                               #当加入repr定义的字符格式的时候会把非映射关系的数据按照tmp定义的格式输出
        tmp = \'%s - %s - %s\'%(self.nid,self.username,self.group_id)
        return tmp


#生成表
def init_db():
    Base.metadata.create_all(engine)
init_db()

Session = sessionmaker(bind=engine)           #会话绑定
session = Session()

session.add_all([                    #插入组数据
    Group(caption=\'DBA\'),
    Group(caption=\'OPS\')
])
session.add_all([                    #插入用户数据
    User(username=\'alex\',group_id=1),
    User(username=\'wanghui\',group_id=2)
])
session.commit()
ret=session.query(User).filter(User.username==\'wanghui\').all()    #将收集的数据存储成为一个list对象
print(ret)
obj=ret[0]
print(obj)
print(obj.username)
print(obj.group_id)
print(obj.nid)
ret1=session.query(User.username).all()     #这样的话可以直接获取数据(加上映射之后就可以取到数据了)
print(ret1)

正向查找:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,Integer,String,ForeignKey,UniqueConstraint,Index
from sqlalchemy.orm import sessionmaker,relationship

engine = create_engine("mysql+pymysql://root:123456@10.70.18.100:3306/zzz",max_overflow=5,encoding=\'utf-8\')    #连接数据库
# engine = create_engine("mysql+pymysql://root:123456@10.70.18.100:3306/zzz",max_overflow=5,encoding=\'utf-8\', echo=True)    #连接数据库
Base = declarative_base()
#建表
class Test(Base):
    __tablename__=\'test\'
    nid=Column(Integer,primary_key=True,autoincrement=True)
    name=Column(String(32))

#一对多表
class Group(Base):
    __tablename__=\'group\'
    nid=Column(Integer,primary_key=True,autoincrement=True)
    caption=Column(String(32))

class User(Base):
    __tablename__=\'user\'
    nid=Column(Integer,primary_key=True,autoincrement=True)
    username=Column(String(32))
    group_id=Column(Integer,ForeignKey(Group.nid))     #和group的id建立关系
    group=relationship(\'Group\',backref=\'uuu\')        #解决查询时候的连表关系,
    def __repr__(self):                               #当加入repr定义的字符格式的时候会把非映射关系的数据按照tmp定义的格式输出
        tmp = \'%s - %s - %s\'%(self.nid,self.username,self.group_id)
        return tmp


#生成表
def init_db():
    Base.metadata.create_all(engine)
init_db()

Session = sessionmaker(bind=engine)           #会话绑定
session = Session()

# session.add_all([                    #插入组数据
#     Group(caption=\'DBA\'),
#     Group(caption=\'OPS\')
# ])
# session.add_all([                    #插入用户数据
#     User(username=\'alex\',group_id=1),
#     User(username=\'wanghui\',group_id=2)
# ])
# session.commit()
#连表操作
#正向查询方式
ret=session.query(User).all()
for obj in ret:    #obj代指user表的nid,obj
    print(obj.nid,obj.username,obj.group_id,obj.group.nid,obj.group.caption)

反向查找:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,Integer,String,ForeignKey,UniqueConstraint,Index
from sqlalchemy.orm import sessionmaker,relationship

engine = create_engine("mysql+pymysql://root:123456@10.70.18.100:3306/zzz",max_overflow=5,encoding=\'utf-8\')    #连接数据库
# engine = create_engine("mysql+pymysql://root:123456@10.70.18.100:3306/zzz",max_overflow=5,encoding=\'utf-8\', echo=True)    #连接数据库
Base = declarative_base()
#建表
class Test(Base):
    __tablename__=\'test\'
    nid=Column(Integer,primary_key=True,autoincrement=True)
    name=Column(String(32))

#一对多表
class Group(Base):
    __tablename__=\'group\'
    nid=Column(Integer,primary_key=True,autoincrement=True)
    caption=Column(String(32))

class User(Base):
    __tablename__=\'user\'
    nid=Column(Integer,primary_key=True,autoincrement=True)
    username=Column(String(32))
    group_id=Column(Integer,ForeignKey(Group.nid))     #和group的id建立关系
    group=relationship(\'Group\',backref=\'uuu\')        #解决查询时候的连表关系,
    def __repr__(self):                               #当加入repr定义的字符格式的时候会把非映射关系的数据按照tmp定义的格式输出
        tmp = \'%s - %s - %s\'%(self.nid,self.username,self.group_id)
        return tmp


#生成表
# def init_db():
#     Base.metadata.create_all(engine)
# init_db()
#
Session = sessionmaker(bind=engine)           #会话绑定
session = Session()
#
# session.add_all([   j                 #插入组数据
#     Group(caption=\'DBA\'),
#     Group(caption=\'OPS\')
# ])
# session.add_all([                    #插入用户数据
#     User(username=\'alex\',group_id=1),
#     User(username=\'wanghui\',group_id=2)
# ])
# session.commit()
#连表操作
# sql=session.query(User.username,Group.caption).join(Group,isouter=True).filter(Group.caption==\'DBA\')
# print(sql)
# ret=session.query(User.username,Group.caption).join(Group,isouter=True).filter(Group.caption==\'DBA\').all()   #isouter:表示left JOIN
# print(ret)
#反向查询
res=session.query(Group).filter(Group.caption==\'DBA\').first()
print(res.nid)
print(res.caption)
print(res.uuu)

多对多数据创建与操作:

多对多使用背景:

多机器,多用户,多权限

类似于下图的格式:

对于主机c1来说都存在与之对应的服务器用户,所以要建立用户和服务器指之间的关联关系,就要出现一张新的表来对应他们之间的关系表:

外键约束;

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,Integer,String,ForeignKey,UniqueConstraint,Index
from sqlalchemy.orm import sessionmaker,relationship

engine = create_engine("mysql+pymysql://root:123456@10.70.18.100:3306/zzz",max_overflow=5,encoding=\'utf-8\')    #连接数据库
# engine = create_engine("mysql+pymysql://root:123456@10.70.18.100:3306/zzz",max_overflow=5,encoding=\'utf-8\', echo=True)    #连接数据库
Base = declarative_base()
#建表
class Group(Base):
    __tablename__=\'group\'
    nid=Column(Integer,primary_key=True,autoincrement=True)
    caption=Column(String(32))

class User(Base):
    __tablename__=\'user\'
    nid=Column(Integer,primary_key=True,autoincrement=True)
    username=Column(String(32))
    group_id=Column(Integer,ForeignKey(Group.nid))     #和group的id建立关系
    group=relationship(\'Group\',backref=\'uuu\')        #解决查询时候的连表关系,
    def __repr__(self):                               #当加入repr定义的字符格式的时候会把非映射关系的数据按照tmp定义的格式输出
        tmp = \'%s - %s - %s\'%(self.nid,self.username,self.group_id)
        return tmp

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)
    host_id=Column(Integer,ForeignKey(\'host.nid\'))
    host_user_id=Column(Integer,ForeignKey(\'host_user.nid\'))

#创建表
# def init_db():
#     Base.metadata.create_all(engine)
# init_db()
Session=sessionmaker(bind=engine)
session=Session()
#创建数据
# session.add_all([
#     Host(hostname=\'c1\',port=22,ip=\'192.168.1.1\'),
#     Host(hostname=\'c2\',port=22,ip=\'192.168.1.2\'),
#     Host(hostname=\'c3\',port=22,ip=\'192.168.1.3\'),
#     Host(hostname=\'c4\',port=22,ip=\'192.168.1.4\'),
#     Host(hostname=\'c5\',port=22,ip=\'192.168.1.5\'),
# ])
# session.add_all([
#     HostUser(username=\'root\'),
#     HostUser(username=\'wanghui\'),
#     HostUser(username=\'zzd\'),
#     HostUser(username=\'ys\'),
# ])
#创建对应关系数据
# session.add_all([
#     HostToHostUser(host_id=1,host_user_id=1),
#     HostToHostUser(host_id=1,host_user_id=2),
#     HostToHostUser(host_id=1,host_user_id=3),
#     HostToHostUser(host_id=2,host_user_id=1),
#     HostToHostUser(host_id=2,host_user_id=2),
#     HostToHostUser(host_id=2,host_user_id=3),
# ])
# session.commit()
#获取主机1中的用户数据

 

 

推荐方式:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,Integer,String,ForeignKey,UniqueConstraint,Index,Table
from sqlalchemy.orm import sessionmaker,relationship

engine = create_engine("mysql+pymysql://root:123456@10.70.18.100:3306/zzz",max_overflow=5,encoding=\'utf-8\')    #连接数据库
# engine = create_engine("mysql+pymysql://root:123456@10.70.18.100:3306/zzz",max_overflow=5,encoding=\'utf-8\', echo=True)    #连接数据库
Base = declarative_base()
#建表
class Group(Base):
    __tablename__=\'group\'
    nid=Column(Integer,primary_key=True,autoincrement=True)
    caption=Column(String(32))

class User(Base):
    __tablename__=\'user\'
    nid=Column(Integer,primary_key=True,autoincrement=True)
    username=Column(String(32))
    group_id=Column(Integer,ForeignKey(Group.nid))     #和group的id建立关系
    group=relationship(\'Group\',backref=\'uuu\')        #解决查询时候的连表关系,
    def __repr__(self):                               #当加入repr定义的字符格式的时候会把非映射关系的数据按照tmp定义的格式输出
        tmp = \'%s - %s - %s\'%(self.nid,self.username,self.group_id)
        return tmp

class HostToHostUser(Base):                                    #关系表
    __tablename__ = \'host_to_host_user\'
    nid=Column(Integer,primary_key=True,autoincrement=True)   #自己的主键
    host_id=Column(Integer,ForeignKey(\'host.nid\'))    #创建host外键
    host_user_id=Column(Integer,ForeignKey(\'host_user.nid\'))  #创建user外键

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))
    host_user=relationship(\'HostUser\',secondary=HostToHostUser.__table__,backref=\'host_list\')    #正向查找和反向查找



class HostUser(Base):
    __tablename__=\'host_user\'
    nid=Column(Integer,primary_key=True,autoincrement=True)
    username=Column(String(32))


#创建表
# def init_db():
#     Base.metadata.create_all(engine)
# init_db()
Session=sessionmaker(bind=engine)
session=Session()
#创建host数据
# session.add_all([
#     Host(hostname=\'c1\',port=22,ip=\'192.168.1.1\'),
#     Host(hostname=\'c2\',port=22,ip=\'192.168.1.2\'),
#     Host(hostname=\'c3\',port=22,ip=\'192.168.1.3\'),
#     Host(hostname=\'c4\',port=22,ip=\'192.168.1.4\'),
#     Host(hostname=\'c5\',port=22,ip=\'192.168.1.5\'),
# ])
#插入用户
# session.add_all([
#     HostUser(username=\'root\'),
#     HostUser(username=\'wanghui\'),
#     HostUser(username=\'zzd\'),
#     HostUser(username=\'ys\'),
# ])
#创建对应关系数据
# session.add_all([
#     HostToHostUser(host_id=1,host_user_id=1),
#     HostToHostUser(host_id=1,host_user_id=2),
#     HostToHostUser(host_id=1,host_user_id=3),
#     HostToHostUser(host_id=2,host_user_id=1),
#     HostToHostUser(host_id=2,host_user_id=),
#     HostToHostUser(host_id=2,host_user_id=3),
# ])
# session.commit()
host_obj=session.query(Host).filter(Host.hostname==\'c1\').first()
print(host_obj.host_user)

整体思想

1.创建表和操作表

2.操作表:

单表操作:转换操作

连表操作:.join

               创建关系:

                             一对多:正向查找,反向查找

                             多对多:多一张关系表

以上是关于day13 SQLAlchemy的主要内容,如果未能解决你的问题,请参考以下文章

Python_Day13_ORM sqlalchemy

Day13 SQLAlchemy连表操作和堡垒机

day11:SqlAlchemy ORM

sqlalchemy - day1

sqlalchemy——单表操作

DAY11-MYSQL之ORM框架SQLAlchemy