标签:
SQLAlchemy是Python编程语言下的一款ORM框架,该框架建立在数据库API之上,使用关系对象映射进行数据库操作,简言之便是:将对象转换成SQL,然后使用数据API执行SQL并获取执行结果。
使用 ORM/Schema Type/SQL Expression Language/Engine/ConnectionPooling/Dialect 所有组件对数据进行操作。根据类创建对象,对象转换成SQL,执行SQL。
1 __author__ = ‘lizheng‘ 2 # !/usr/bin/env python 3 #-*- coding:utf-8 -*- 4 5 6 from sqlalchemy import create_engine 7 from sqlalchemy.ext.declarative import declarative_base 8 from sqlalchemy import Column, Integer, String, ForeignKey, and_, or_ , func 9 from sqlalchemy.orm import sessionmaker, relationship 10 11 Base = declarative_base() # 生成一个sqlORM 基类 12 13 engine = create_engine(‘mysql+pymysql://root:root@localhost:3306/test?charset=utf8‘, echo=False) # echo显示执行过程 14 15 class Host(Base): 16 __tablename__ = ‘hosts‘ 17 id = Column(Integer, primary_key=True, autoincrement=True) 18 hostname = Column(String(64), unique=True, nullable=False) 19 ip_addr = Column(String(128), unique=True, nullable=False) 20 port = Column(Integer, default=22) 21 group_id = Column(Integer, ForeignKey(‘group.id‘)) 22 #backref为Group关联Host时用的对象名 23 group = relationship(‘Group‘, backref=‘host_list‘) 24 25 class Group(Base): 26 __tablename__ = ‘group‘ 27 id = Column(Integer, primary_key=True) 28 name = Column(String(64), unique=True, nullable=False) 29 30 Base.metadata.create_all(engine) # 创建所有表结构 31 if __name__ == ‘__main__‘: 32 # 创建与数据库的会话session class,注意:这里返回给session的是个class,不是实例 33 SessionCls = sessionmaker(bind=engine) 34 session = SessionCls() # 创建实例 35 h = session.query(Host).filter(Host.hostname==‘server‘).first() # first 结果为class属性 36 print(‘host group name -->‘, h.group.name) 37 g = session.query(Group).filter(Group.name==‘g2‘).first() 38 #g.host_list为Host对象 39 for i in g.host_list: 40 print(‘group 2 hostname -->‘, g.host_list.hostname) 41 # h1 = Host(hostname=‘localhost‘, ip_addr=‘127.0.0.1‘) 42 # h2 = Host(hostname=‘ubuntu‘, ip_addr=‘192.168.1.1‘, port=8888) 43 # h3 = Host(hostname=‘server2‘, ip_addr=‘192.168.2.22‘, port=1234,group_id = 2) 44 # session.add_all([h3,]) 45 # session.commit() 46 # g1 = Group(name=‘g1‘) 47 # g2 = Group(name=‘g2‘) 48 # g3 = Group(name=‘g3‘) 49 # session.add_all([g1,g2,g3]) 50 # session.commit() 51 # res = session.query(Host).filter(Host.hostname==‘server‘).all() # all 结果为列表 52 # res = session.query(Host).filter(Host.hostname==‘server‘).first() # first 结果为class属性 53 # print(‘host group name -->‘, res.group.name) 54 # print(‘res type-->‘, type(res)) 55 # g = session.query(Group).filter(Group.name==‘g2‘).first() 56 # print(‘group 2 hostname -->‘, g.host_list) 57 # print(‘group name to hostname -->‘, g.host_list.hostname) 58 # print(‘group-->‘, g) 59 # obj = session.query(Host, func.count()).group_by(Host.group_id).all() 60 # print(obj) 61 # session.commit()
标签:
原文地址:http://www.cnblogs.com/lizheng19822003/p/5396116.html