day40--mysql step4 SQLAlchemy

1、unique = True 表示启动唯一索

2、有add 必须有commit这样数据才会提交

3、ORM功能

#!/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:123@127.0.0.1:3306/t1", max_overflow=5)
 
Base = declarative_base()
 
# 创建单表
class Users(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String(32))
    extra = Column(String(16))
 
    __table_args__ = (
    UniqueConstraint('id', 'name', name='uix_id_name'),
        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"))
 
 
# 多对多
class Group(Base):
    __tablename__ = 'group'
    id = Column(Integer, primary_key=True)
    name = Column(String(64), unique=True, nullable=False)
    port = Column(Integer, default=22)
 
 
class Server(Base):
    __tablename__ = 'server'
 
    id = Column(Integer, primary_key=True, autoincrement=True)
    hostname = Column(String(64), unique=True, nullable=False)
 
 
class ServerToGroup(Base):
    __tablename__ = 'servertogroup'
    nid = Column(Integer, primary_key=True, autoincrement=True)
    server_id = Column(Integer, ForeignKey('server.id'))
    group_id = Column(Integer, ForeignKey('group.id'))
 
 
def init_db():
    Base.metadata.create_all(engine)
 
 
def drop_db():
    Base.metadata.drop_all(engine)
建表
#!/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:123@127.0.0.1:3306/t1", max_overflow=5)

Base = declarative_base()

# 创建单表
class Users(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String(32))
    extra = Column(String(16))

    __table_args__ = (
    UniqueConstraint('id', 'name', name='uix_id_name'),
        Index('ix_id_name', 'name', 'extra'),
    )

    def __repr__(self):
        return "%s-%s" %(self.id, self.name)

# 一对多
class Favor(Base):
    __tablename__ = 'favor'
    nid = Column(Integer, primary_key=True)
    caption = Column(String(50), default='red', unique=True)

    def __repr__(self):
        return "%s-%s" %(self.nid, self.caption)

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 = relationship("Favor", backref='pers')

# 多对多
class ServerToGroup(Base):
    __tablename__ = 'servertogroup'
    nid = Column(Integer, primary_key=True, autoincrement=True)
    server_id = Column(Integer, ForeignKey('server.id'))
    group_id = Column(Integer, ForeignKey('group.id'))
    group = relationship("Group", backref='s2g')
    server = relationship("Server", backref='s2g')

class Group(Base):
    __tablename__ = 'group'
    id = Column(Integer, primary_key=True)
    name = Column(String(64), unique=True, nullable=False)
    port = Column(Integer, default=22)
    # group = relationship('Group',secondary=ServerToGroup,backref='host_list')


class Server(Base):
    __tablename__ = 'server'

    id = Column(Integer, primary_key=True, autoincrement=True)
    hostname = Column(String(64), unique=True, nullable=False)




def init_db():
    Base.metadata.create_all(engine)


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


Session = sessionmaker(bind=engine)
session = Session()

表结构 + 数据库连接
连接db

 

#
obj = Users(name="alex0", extra='sb')
session.add(obj)
session.add_all([
    Users(name="alex1", extra='sb'),
    Users(name="alex2", extra='sb'),
])
session.commit()
#
session.query(Users).filter(Users.id > 2).delete()
session.commit()
#
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.query(Users).filter(Users.id > 2).update({"num": Users.num + 1}, synchronize_session="evaluate")
session.commit()
#
ret = session.query(Users).all()
ret = session.query(Users.name, Users.extra).all()
ret = session.query(Users).filter_by(name='alex').all()
ret = session.query(Users).filter_by(name='alex').first()

ret = session.query(Users).filter(text("id<:value and name=:name")).params(value=224, name='fred').order_by(User.id).all()

ret = session.query(Users).from_statement(text("SELECT * FROM users where name=:name")).params(name='ed').all()
#其他
# 条件
ret = session.query(Users).filter_by(name='alex').all()
ret = session.query(Users).filter(Users.id > 1, Users.name == 'eric').all()
ret = session.query(Users).filter(Users.id.between(1, 3), Users.name == 'eric').all()
ret = session.query(Users).filter(Users.id.in_([1,3,4])).all()
ret = session.query(Users).filter(~Users.id.in_([1,3,4])).all()
ret = session.query(Users).filter(Users.id.in_(session.query(Users.id).filter_by(name='eric'))).all()
from sqlalchemy import and_, or_
ret = session.query(Users).filter(and_(Users.id > 3, Users.name == 'eric')).all()
ret = session.query(Users).filter(or_(Users.id < 2, Users.name == 'eric')).all()
ret = session.query(Users).filter(
    or_(
        Users.id < 2,
        and_(Users.name == 'eric', Users.id > 3),
        Users.extra != ""
    )).all()


# 通配符
ret = session.query(Users).filter(Users.name.like('e%')).all()
ret = session.query(Users).filter(~Users.name.like('e%')).all()

# 限制
ret = session.query(Users)[1:2]

# 排序
ret = session.query(Users).order_by(Users.name.desc()).all()
ret = session.query(Users).order_by(Users.name.desc(), Users.id.asc()).all()

# 分组
from sqlalchemy.sql import func

ret = session.query(Users).group_by(Users.extra).all()
ret = session.query(
    func.max(Users.id),
    func.sum(Users.id),
    func.min(Users.id)).group_by(Users.name).all()

ret = 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()
数据库操作

条件用 filter单值用filter_by

4、示例代码

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#coding:utf8
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import sessionmaker
print(sqlalchemy.__version__)


engine = create_engine('mysql+pymysql://sysadmin:password01!@10.10.8.12:3306/q2')

Base = declarative_base()#生成一个SQLORM基类

class User(Base):
    __tablename__ = 'sqlalchemydemo'

    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(40))
    fullname = Column(String(40))
    password = Column(String(40))

    def __repr__(self):
       return "<User(name='%s', fullname='%s', password='%s')>" % (
                            self.name, self.fullname, self.password)

Base.metadata.create_all(engine)  #创建所有表结构
# Base.metadata.drop_all(engine)  # 删除所有表
# ed_user = User(name='xiaoyu', fullname='Xiaoyu Liu', password='123')
# print(ed_user)
# #这两行触发sessionmaker类下的__call__方法,return得到 Session实例,赋给变量session,所以session可以调用Session类下的add,add_all等方法
MySession = sessionmaker(bind=engine)
session = MySession()

# session.add(ed_user)    ##添加数据
# our_user = session.query(User).filter_by(name='ed').first()
# SELECT * FROM users WHERE name="ed" LIMIT 1;
# session.add_all([
#     User(name='alex', fullname='Alex Li', password='456'),
#     User(name='alex', fullname='Alex old', password='789'),
#     User(name='peiqi', fullname='Peiqi Wu', password='sxsxsx')])
#
# session.commit()

#print(">>>",session.query(User).filter_by(name='ed').first())
# print(session.query(User).all())  #表内容

# for row in session.query(User).order_by(User.id):
#      print(row)
# for row in session.query(User).filter(User.name.in_(['alex', 'wendy', 'jack'])):#这里的名字是完全匹配
#     print(row)
# for row in session.query(User).filter(~User.name.in_(['ed', 'wendy', 'jack'])):
#     print(row)
# print(session.query(User).filter(User.name == 'ed').count())
from sqlalchemy import and_, or_

# for row in session.query(User).filter(and_(User.name == 'ed', User.fullname == 'Ed Jones')):
#     print(row)
for row in session.query(User).filter(or_(User.name == 'ed', User.fullname == 'wendy')):
    print(row)
lone
#!/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://sysadmin:password01!@10.10.8.12:3306/q2')

Base = declarative_base()

class Son(Base):
    __tablename__ = 'son'
    id = Column(Integer, primary_key=True)
    name = Column(String(32))
    age = Column(String(16))

    father_id = Column(Integer, ForeignKey('father.id'))
    # father = relationship('Father')

    # __table_args__ = (
    #     UniqueConstraint('id', 'name', name='uix_id_name'),
    #     Index('ix_id_name', 'name', 'extra'),
    # )
    #

class Father(Base):
    __tablename__ = 'father'

    id = Column(Integer, primary_key=True)
    name = Column(String(32))
    age = Column(String(16))
    son = relationship('Son', backref = 'father')


Base.metadata.create_all(engine)

Session = sessionmaker(bind=engine)
session = Session()


# ret3 = session.query(Father).filter_by(id=1).all()
# ret4 = session.query(Father).filter_by(id=4).first()
# for ii in ret4.son:
#     print(ii.name)

# s1 = session.query(Son).filter_by(id=1).first()
# print(s1.father.name,s1.name)

ret4 = session.query(Father).filter_by(id=4).first()
w4 = Son(name = 'little alvin4',age = 5)
ret4.son.append(w4)
session.add(ret4)
session.commit()

# print(ret3)
# for i in ret3:
#     print(i.name)

#
# ret1 = session.query(Father.name.label('kkk'), Son.name.label('ppp')).join(Son)
#
# ret = session.query(Father.name.label('kkk'), Son.name.label('ppp')).join(Son).all()
# print(ret1)
# print(ret)
#
# print(len(ret))
# for ii in ret:
#     print(ii)
# # f1 = Father(name='alvin4', age=50)
# w1 = Son(name='little alvin1', age=4, father_id = 2)
# w2 = Son(name='little alvin2', age=5, father_id = 2)
# #
# # f1.son = [w1, w2]
# # session.add(f1)
#
# session.add_all([w1,w2])
# session.commit()
one2many
#!/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://sysadmin:password01!@10.10.8.12:3306/q2?charset=utf8')
Base = declarative_base()

class Men_to_Wemon1(Base):
    __tablename__ = 'men_to_wemon1'
    nid = Column(Integer, primary_key=True)
    men_id = Column(Integer, ForeignKey('men1.id'))
    women_id = Column(Integer, ForeignKey('women1.id'))

class Men1(Base):
    __tablename__ = 'men1'
    id = Column(Integer, primary_key=True)
    name = Column(String(32))
    age= Column(String(16))

class Women1(Base):
    __tablename__ ='women1'
    id = Column(Integer, primary_key=True)
    name = Column(String(32))
    age= Column(String(16))
    bf=relationship("Men1",secondary=Men_to_Wemon1.__table__,backref='gf')

Base.metadata.create_all(engine)
#
Session = sessionmaker(bind=engine)
session = Session()
#
# m1=Men1(name='alex',age=18)
# m2=Men1(name='wusir',age=18)
# w1=Women1(name='如花',age=40)
# w2=Women1(name='铁锤',age=45)

# t1 = Men_to_Wemon1(men_id=1,women_id=2)

m1 = session.query(Men1).filter_by(id = 2).first()
w1 = session.query(Women1).all()
m1.gf=w1
# m1.gf=[w1,w2]
# w1.bf=[m1,m2]
session.add_all([m1,])
# session.add_all([m1,m2,w1,w2])
# session.add(t1)
session.commit()
many2many
#!/usr/bin/env python
# -*- coding:utf-8 -*-

from sqlalchemy import create_engine, and_, or_, func, Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey
from  sqlalchemy.orm import sessionmaker, relationship

engine = create_engine('mysql+pymysql://sysadmin:password01!@10.10.8.12:3306/q2?charset=utf8')

Base = declarative_base()  # 生成一个SqlORM 基类


class HostToGroup(Base):
    __tablename__ = 'host_2_group'
    nid = Column(Integer, primary_key=True)
    host_id = Column(Integer, ForeignKey("host.id"))
    group_id = Column(Integer, ForeignKey("group.id"))


class Host(Base):
    __tablename__ = 'host'

    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)
    group = relationship('Group',
                         secondary=HostToGroup.__table__,
                         backref='host_list')

    # group =relationship("Group",back_populates='host_list')
    def __repr__(self):
        return "<id=%s,hostname=%s, ip_addr=%s>" % (self.id,
                                                    self.hostname,
                                                    self.ip_addr)


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

    def __repr__(self):
        return "<id=%s,name=%s>" % (self.id, self.name)


Base.metadata.create_all(engine)  # 创建所有表结构

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])
    # h1 = Host(hostname='h1',ip_addr='192.168.1.56')
    # h2 = Host(hostname='h2',ip_addr='192.168.1.57',port=10000)
    # h3 = Host(hostname='ubuntu',ip_addr='192.168.1.58',port=10000)
    #
    # h1.group=[g2,g4]
    # session.add_all([h1,h2,h3])
    # session.commit()


    # groups = session.query(Group).all()
    # h2 = session.query(Host).filter(Host.hostname=='h2').first()
    # h2.group = groups[:-1]
    # print("===========>",h2.group)



    g4 = session.query(Group).filter(Group.name=='g4').first()
    print(g4)
    obj1 = session.query(Host).filter(Host.hostname=='h1').update({'port':444})
    obj2 = session.query(Host).filter(Host.hostname=='h1').first()

    # g4.host_list.append(obj2)
    obj2.group.append(g4)

    #
    # obj2= session.query(Host).filter(Host.hostname=='h1').first()
    # print("h1:",obj2.group)
    # print("g:",g4.host_list )





    session.commit()
many2many2

 

posted @ 2018-04-07 08:18  john221100  阅读(184)  评论(0编辑  收藏  举报