• 使用sqlalchemy


     1 from sqlalchemy import create_engine
     2 from sqlalchemy.ext.declarative import declarative_base
     3 from sqlalchemy import Column,Integer,String,CHAR,and_,or_,ForeignKey,UniqueConstraint,Index
     4 from  sqlalchemy.orm import sessionmaker,relationship
     5 
     6 engine = create_engine('mysql+pymysql://root@127.0.0.1:3306/ces?charset=utf8') #连接数据库
     7 Base = declarative_base()#生成一个SQLORM基类
     8 
     9 class User(Base):
    10      __tablename__ = 'users'
    11      id = Column(Integer,primary_key=True,autoincrement=True)
    12      name = Column(String(32))
    13      fullname = Column(String(32))
    14      password = Column(CHAR(32))
    15     extra = Column(String(16))
    16     
    17      __table_args__ = (
    18          UniqueConstraint('id', 'name', name='uix_id_name'),
    19          Index('ix_id_name', 'name', 'extra'),
    20      )
    21 
    22     def __repr__(self):
    23          return "<User(name='%s',fullname='%s',password='%s')>%(self.name,self.fullname,self.passwpord)"

    一对多

     1 class Favor(Base):
     2     __tablename__ = 'favor'
     3     nid = Column(Integer,primary_key=True,autoincrement=True)
     4     caption = Column(String(50),default="red",unique=True)
     5 
     6 class Person(Base):
     7     __tablename__ = 'person'
     8     nid = Column(Integer,primary_key=True,autoincrement=True)
     9     name = Column(String(50),index=True,nullable=True)
    10     favor_id = Column(Integer,ForeignKey('favor.nid'))

    多对多

     1 class Group(Base):
     2     __tablename__ = 'group'
     3     id = Column(Integer,primary_key=True)
     4     name = Column(String(64),unique=True,nullable=False)
     5     port = Column(Integer,default=22)
     6 
     7 class Server(Base):
     8     __tablename__ = 'server'
     9     id = Column(Integer,primary_key=True,autoincrement=True)
    10     hostname = Column(String(64),unique=True,nullable=False)
    11 
    12 class ServerToGroup(Base):
    13     __tablename__ = 'servertogroup'
    14     nid = Column(Integer,primary_key=True,autoincrement=True)
    15     server_id = Column(Integer,ForeignKey('server.id'))
    16     group_id = Column(Integer,ForeignKey('group.id'))
    17 class Son(Base):
    18     __tablename__ = 'son'
    19     id = Column(Integer,primary_key=True,autoincrement=True)
    20     name = Column(String(50))
    21     age = Column(String(16))
    22     father_id = Column(Integer,ForeignKey('father.id'))
    23 
    24 class Father(Base):
    25     __tablename__ = 'father'
    26     id = Column(Integer,primary_key=True,autoincrement=True)
    27     name = Column(String(50))
    28     age = Column(String(12))
    29     son = relationship('Son',backref="father")

    添加数据

     1 Base.metadata.create_all(engine) #创建所有表结构
     2 MySession = sessionmaker(bind=engine)
     3 session = MySession()
     4 ed_user = User(name="xiaoyu",fullname="Xiaoyu Lu",password="123")
     5 session.add(ed_user ) 添加一条数据
     6 session.commit()
     7 
     8 session.add_all([
     9      User(name="张三",fullname="3",password="456"),
    10      User(name="王五",fullname="5",password="789"),
    11      User(name="马六",fullname="6",password="sxsxsx")
    12 ])#添加多条数据
    13 
    14 session.commit()
    15 
    16 session.close()

    删除数据

     1 session.query(Users).filter(Users.id > 2).delete() 

    修改数据

    1 #把ID大于2的名字都改为099
    2 session.query(Users).filter(Users.id > 2).update({"name" : "099"})
    3 #把ID大于2的名字,在原有的名字基础上加099
    4 session.query(Users).filter(Users.id > 2).update({Users.name: Users.name + "099"}, synchronize_session=False)
    5 #把ID大于2的数值都加1
    6 session.query(Users).filter(Users.id > 2).update({"num": Users.num + 1}, synchronize_session="evaluate")
    7 session.commit()

    查询数据

    #排序,从小到大读取数据
    for row in session.query(User).order_by(User.id):
         print(row)
    #按条件查询查询(查询数据库中在列表里面是否有相同的内容,如果有就打印,没有则不打印)
    for row in session.query(User).filter(User.name.in_(['wangwu','zhansgan','jack'])):
         print(row)
    #按条件查询查询,与上面的刚好相反,如果存在不打印,不存在打印
     for row in session.query(User).filter(~User.name.in_(['wangwu','zhansgan','jack'])):
         print(row)
    #统计有多少条内
    session.query(User).filter(User.name == 'wangwu').count()
    session.query(User).filter_by(id=1).count()
    #读取多条
    ret = session.query(Users).filter_by(name='wangwu').all()
    #读取一条 ret = session.query(Users).filter_by(name='wangwu').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()
  • 相关阅读:
    ExtAspNet新版本发布v2.0beta4
    自己实现Rich Text Editor
    ExtAspNet应用技巧(五) 动态创建工具栏菜单
    IronPython的Hello World
    关于“跨语言调用”和“CLS(公共语言规范)”的一点体会
    文档,又是文档
    对项目目标的一点想法
    推荐一个WMI的查询分析器
    几个很不错的.NET 相关的FAQ和例子代码的连接
    用IronPython写winform程序
  • 原文地址:https://www.cnblogs.com/xb88/p/8016555.html
Copyright © 2020-2023  润新知