sqlalchemy

外键:分表后如果不做约束,与分表后不相符的值也可以插入,为了制约这种行为所以就出现了外键关联,一个字段外键关联到分表的那个字段后,必须输入那个字段中有的值

一对多

多对多

sqlalchemy 中的方法:

  1. from sqlalchemy import create_engine
  2. from sqlalchemy.ext.declarative import declarative_base
  3. from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint
  4. from sqlalchemy.orm import sessionmaker, relationships

1、一对多

复习时候做的例子

  1. from sqlalchemy import create_engine
  2. from sqlalchemy.ext.declarative import declarative_base
  3. from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint
  4. from sqlalchemy.orm import sessionmaker, relationships
  5.  
  6. #数据库连接
  7. engine = create_engine("mysql+pymysql://root:123@192.168.56.5:3306/s13", max_overflow=) #mysql需要授权本主机
  8.  
  9. Base = declarative_base()
  10.  
  11. class User(Base):
  12. __tablename__ = "user" #表名叫User
  13. nid = Column(Integer, primary_key=True, autoincrement=True ) #Column表中的列的关键字 , Integer,整数, primary_key=True 主键, autoincrement=True自增
    username = Column(String()) #第二列为 名字 的一列
    group_id = Column(Integer, ForeignKey("group.nid")) #和 group的nid 建立外键,user和group的位置谁在上面都可以.
  1. class Group(Base):
    __tablename__ = "group"
    nid = Column(Integer, primary_key=True, autoincrement=True)
    caption = Column(String())
  1. def init_db():
    #创建表
    Base.metadata.create_all(engine)
  2.  
  3. def drop_db():
    #删除表
    Base.metadata.drop_all(engine)
  4.  
  5. #init_db()
    Session = sessionmaker(bind=engine) #通过engine 的对象开始创建表中的内容
    session = Session()
  6.  
  7. 单条插入数据的方法
      #因为人在组中,人的外键是组,所以要先创建组中的数据,要不然就user就没法用组中的这些字段了
      session.add(Group(caption='dba'))
      session.add(Group(caption='yunwei'))
      session.add(Group(caption='jiankong'))
      session.commit()
  1.  
  1. 一、#创建表结构
  2. class Host(Base): #所有的子类都继承这个基类
  3. #创建表结构
  4. __tablename__ = 'hosts'
  5. id = Column(Integer, primary_key=True,autoincrement=True) #Colum 表中的列 , Integer,整数, primary_key=True 主键, autoincrement=True自增
    hostname = Column(String(64),unique=True,nullable=False)
    group_id = Column(Integer,ForeignKey('groups.id')) #创建外面hosts中的group_id关联到work_group的id
    group = relationship("Group") #要写大写的实例名字通过映射的关系 , 能在hosts表中查询到外键表中的其他value
  1.    def __repr__(self):
  1. return "<id = %s,jump_user_name=%s>" % (self.id, self.username)
  1. class Group(Base): __tablename__= 'groups'
        id = Column(Integer,primary_key=True) #自动自增,主键  
        name = Column(String(64),unique=True,nullable=False)
  2.  
  3. Base.metadata.create_all(engine) #执行上面的sql
    图示: group
    1 web 
      2 db host hostname   
  4.  
  5.   外键group_id
    1   nginx        1
    2   mysql       2
  6.  
  7. 这时候我们把hostgroup_id group.id 做了外键关联
    意思就是说我必须有group组,在能创建host组,或者说我们也可以先把host的这是为可以为空,这样就可以先填写host这涨表了
  8.  
  9. 二、#插入数据
  1. 第一种插入数据的方法
    1、我们可以直接插入host主机
    h1 = Host(hostname = "nginx")
    h2 = Host(hostname = "mysql")
  1. session.add_all([h1,h2])
    session.commit()
  1. 2、然后我们再插入group数据
  2.  
  3. g1 = Group(name = 'web')
    g2 = Group(name = 'db')
  4.  
  5. session.add_all([g1,g2])
    session.commit()
  1. 3、再做hostgroup关联(就是把hostgroup_id 改下)
  1. g1 = session.query(Group).filter(Group.name == "web").first()     #找出g1的对象
    h1 = session.query(Host).filter(Host.hostname=='nginx').update({"group_id":g1.id})
    session.commit()
  2.  
  3. #插入数据时也可以以主动指定外键的值,但是不要超过被关联的键的范围就可以
  1. h1 = Host(hostname = "nginx",group_id = 1)
    h2 = Host(hostname = "mysql",group_id = 2)
  1. h3 = Host(hostname = "origer",group_id = 3) 这样就报错了
  1. 第二种插入数据的方法
    先把group表值插进去,然后再插入host
  1. SessionCls = sessionmaker(bind=engine)
    session = SessionCls()
  2.  
  3. g1 = Group(name = 'web') #先插入group表
    g2 = Group(name = 'db')
    session.add_all([g1,g2])
    #
    gw = session.query(Group).filter(Group.name == 'web').first() #不用提交g1就可以在内存中查询到group中对应的数据,
    gb = session.query(Group).filter(Group.name == 'db').first()
    h1 = Host(hostname = "nginx",group_id = gw.id)            #直接复制给h1使用
    h2 = Host(hostname = "mysql",group_id = gb.id)
    session.add_all([h1,h2])
    session.commit()
  1. 三、查询
  2.  
  3. 1all first
  1. all()
    gw = session.query(Group).all()
    print(gw)
    [<__main__.Group object at 0x0000003438C3F0F0>, <__main__.Group object at 0x0000003438C3F160>] #拿到了跟Group有关的所有数据,是个列表
  1. print(gw[0].name)
    db
    print(gw[0].id)
    2

  1. first()
    gw = session.query(Group).first()
  1. print(gw)
    <__main__.Group object at 0x000000C703531208> #这个就是获取匹配到的第一个对象
  1. print(gw.name)
    db
    print(gw.id)
    2
  2.  
  3. 2query()
  1. query中是要查的表,里面放的是表的类名,这里也是有2中情况
  2.  
  3. queryclass
  1. gw = session.query(Group).all()
    print(gw)
    [<__main__.Group object at 0x000000446E0C1080>, <__main__.Group object at 0x000000446E0C10F0>] #这样知道的是所有的类对象,是个列表
  2.  
  3. queryclass.args
  1. gw = session.query(Group.name).all()
    print(gw)
    [('db',), ('web',)]
  2.  
  3. 3、连表查询
  1. SessionCls = sessionmaker(bind=engine)
    session = SessionCls()
  2.  
  3. ajoin inner join
    gw = session.query(Group).join(Host).all()
    print(gw)
    [<__main__.Group object at 0x0000002B1B345860>]
  1.  
  1. bisouter=True lelf join
  1. gw = session.query(Host).join(Group,isouter=True).all()
    print(gw)
    [hostanme : nginx  -  group_id = 1, hostanme : mysql  -  group_id = 1]

+----+----------+----------+------+------+
| id | hostname | group_id | id | name   |
+----+----------+----------+------+------+
| 1 | nginx    | 1     | 1   | web  |
| 2 | mysql    | 1     | 1   | web  |
+----+----------+----------+------+------+

上图发现,我们获取到的只是host表里的内容,并没有group中的内容

c、我如果我们想要把host表中和gorup中的内容都获取到

  1. gw = session.query(Host,Group).join(Group,isouter=True).all()
    print(gw)
    [(hostanme : nginx  -  group_id = 1, <__main__.Group object at 0x000000B3C53140B8>), (hostanme : mysql  -  group_id = 1, <__main__.Group object at 0x000000B3C53140B8>)]
  2.  
  3. d、我们想要拿到准确的内容,不要对象怎么做?
  1. gw = session.query(Host.hostname,Group.name).join(Group,isouter=True).all()
    print(gw)
    [('nginx', 'web'), ('mysql', 'web')]

使用join固然可以查到我们想要的东西,但是sqlalchemy又帮我们封装了一个很好用的东西

  1. relationship(“Class”)
  1. class Host(Base): #所有的子类都继承这个基类
  2. #创建表结构
  3. __tablename__ = 'hosts'
  4. id = Column(Integer, primary_key=True,autoincrement=True)
  5. hostname = Column(String(64),unique=True,nullable=False)
  6. group_id = Column(Integer,ForeignKey('groups.id')) #创建外面hosts中的group_id关联到work_group的id
  7. group = relationship("Group",backref="host") #要写大写的实例名字通过映射的关系 , 能在hosts表中查询到外键表中的其他value
      #一般情况下foreignkey和relationship是在一起
  8.  
  9. #通过Host正向查找主机名是nginx的外键关联的是那个组
  1. obj = session.query(Host).filter(Host.hostname == 'nginx').first()
    print(obj.group.name)
  2.  
  3. #通过Group正向查找组名是web的都有哪些主机
  1. obj2 = session.query(Group).filter(Group.name == "web").first() 先找到的obj2是组为web的一样group主句
    #和obj2有关系的host中是有2台关联着group的web
    for h in obj2.host:
    print(h.hostname)

  nginx
  mysql

  1.  
  1.  

自定义查询返回值:

  1. class JumpUser(Base):
  2. __tablename__ = 'jump_user'
  3. id = Column(Integer, primary_key=True, autoincrement=True)
  4. username = Column(Integer,unique=True,nullable=False)
  5. passwd = Column(Integer,nullable=False)
  6. groups = relationship("Group",secondary=lambda : JumpUser_2_Group.__table__,backref='jumpuser_list')
  7. host_list = relationship("HostUser", secondary=lambda: JumpUser_2_HostUser.__table__, backref='jumpuser_list')
  8. def __repr__(self):
  9. return "<id = %s,jump_user_name=%s>" % (self.id, self.username)
  10.  
  11. repr中我们使用什么做返回值,在查询时就返回什么

  

python_way day13 sqlalchemy的更多相关文章

  1. python_way day12 sqlalchemy,原生mysql命令

    python_way day12  sqlalchemy,mysql原生命令 1.sqlalchemy 2.mysql 原生命令 一,sqlalchemy SQLAlchemy本身无法操作数据库,其必 ...

  2. Day13 SQLAlchemy连表操作和堡垒机

    一.数据库操作 1.创建表.插入数据和一对多查询 #!/usr/bin/env python # -*- coding: utf-8 -*- # Author: wanghuafeng from sq ...

  3. Python学习-day13 SqlAlchemy

    本节内容 ORM介绍 sqlalchemy安装 sqlalchemy基本使用 多外键关联 多对多关系 表结构设计作业 1. ORM介绍 orm英文全称object relational mapping ...

  4. day13 SQLAlchemy

    ORM:也叫关系对象映射 本篇要点: 原生模块 pymsql ORM框架 SQLAchemy pymysql pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同. 需 ...

  5. python_way day13 paramiko

    paramiko 一.安装 pip3 install paramiko 二.使用 1.SSHClient 用于连接远程服务器并执行基本命令 import paramiko # 创建SSH对象 ssh ...

  6. SQLALchemy(连表)、paramiko

    本节内容:

  7. python运维开发(十三)----SQLalchemy和paramiko续

    内容目录: ORM架构SQLalchemy Paramiko SQLalchemy对表的操作 使用 ORM/Schema Type/SQL Expression Language/Engine/Con ...

  8. Part01、sqlalchemy 使用

    一.ORM         连表               一对多               1.创建表,主动指定外键约束.               2.操作.                 ...

  9. sqlalchemy学习

    sqlalchemy官网API参考 原文作为一个Pythoner,不会SQLAlchemy都不好意思跟同行打招呼! #作者:笑虎 #链接:https://zhuanlan.zhihu.com/p/23 ...

随机推荐

  1. 【python cookbook】【字符串与文本】13.对齐文本字符串

    问题:以某种对齐方式将文本做格式化处理 解决方案: 1.针对字符串:ljust().rjust().center()方法 2.针对任何值,更加通用的:format()  更多内容:https://do ...

  2. git 用法

    git init #创建仓库git add _filename #添加文件到缓冲区git commit -m "msg" #提交更新,从缓冲区提交到版本库git status #查 ...

  3. 微信清理H5真的太早了?这会是应用号发布的前兆吗

    三少爷的剑  2016-04-18 21:05 收藏35 评论7   两天之内,整个 H5 游戏创业陷入了两年狂热期以来最冷的冰点. 每一个正在忙于 H5 小游戏开发的开发者都在忙于砍掉游戏代码中有关 ...

  4. Apache httpd和JBoss构建高可用集群环境

    1. 前言 集群是指把不同的服务器集中在一起,组成一个服务器集合,这个集合给客户端提供一个虚拟的平台,使客户端在不知道服务器集合结构的情况下对这一服务器集合进行部署应用.获取服务等操作.集群是企业应用 ...

  5. ios tabbar 文字位置

    [nav.tabBarItem setTitlePositionAdjustment)];

  6. Who's in the Middle 分类: POJ 2015-06-12 19:45 11人阅读 评论(0) 收藏

    Who's in the Middle Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 34155   Accepted: 1 ...

  7. git: fatal unable to auto-detect email address

    参考:http://stackoverflow.com/questions/25671785/git-fatal-unable-to-auto-detect-email-address 正确使用命令: ...

  8. selenium帮助手册以及 webdriver的各种driver

    帮助手册 http://selenium-python.readthedocs.io/locating-elements.html 转载于:http://blog.csdn.net/five3/art ...

  9. python 数据加密以及生成token和token验证

    代码如下: # -*- coding: utf-8 -*- from passlib.apps import custom_app_context as pwd_context import conf ...

  10. flash压力测试

    涉及目录: vendor/mediatek/proprietary/bootable/bootloader/preloader/platform/mt6735/src/drivers/inc/dram ...