这里是你的通告内容

春生

Be humble, communicate clearly, and respect others.

Flask使用SQLAlchemy连接mysql

连接

from sqlalchemy.ext.declarative import declarative_base  # 要继承这个类
from sqlalchemy import Column  # 写字段 条件
from sqlalchemy import Integer,String,Text,Date,DateTime
from sqlalchemy import create_engine  #  链接数据库

 # 单独执行 model 文件
Base = declarative_base()

class Users(Base):
    __tablename__ = 'users'  # 要建的 表名

    id = Column(Integer, primary_key=True)  #
    name = Column(String(32), index=True, nullable=False)  # index加 索引    nullable 为空
    depart_id = Column(Integer)         # Integer  int

def create_all():
    '''
    建表
    :return:
    '''
    engine = create_engine(
        "mysql+pymysql://root:123456@127.0.0.1:3306/db2?charset=utf8",
        max_overflow=0,  # 超过连接池大小外最多创建的连接
        pool_size=5,  # 连接池大小
        pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
        pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
    )

    Base.metadata.create_all(engine)

def drop_all():
    '''
    删表
    :return:
    '''
    engine = create_engine(
        "mysql+pymysql://root:123456@127.0.0.1:3306/db2?charset=utf8",
        max_overflow=0,  # 超过连接池大小外最多创建的连接
        pool_size=5,  # 连接池大小
        pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
        pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
    )
    Base.metadata.drop_all(engine)

if __name__ == '__main__':
    drop_all()  
    create_all()

 

models.py

 

views.py

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from models import Users

# 创建引擎
engine = create_engine(
        "mysql+pymysql://root:123456@127.0.0.1:3306/s9day120?charset=utf8",
        max_overflow=0,  # 超过连接池大小外最多创建的连接
        pool_size=5,  # 连接池大小
        pool_timeout=30,  # 池中没有线程最多等待的时间,否则报错
        pool_recycle=-1  # 多久之后对线程池中的线程进行一次连接的回收(重置)
    )

# 根据引擎创建session工厂
SessionFactory = sessionmaker(bind=engine)

# 用session工厂创建一个session对象
session = SessionFactory()

..........
# 根据Users类对users表进行增删改查
..........

# 关闭session
session.close()

 操作

obj = Users(name='alex')
session.add(obj)
session.commit()

session.add_all([
        Users(name='小东北'),
        Users(name='龙泰')
])
session.commit()

session.query(Users).filter(Users.id >= 2).delete()
session.commit()

session.query(Users).filter(Users.id == 4).update({Users.name:'东北'})
session.query(Users).filter(Users.id == 4).update({'name':'小东北'})
session.query(Users).filter(Users.id == 4).update({'name':Users.name+"DSB"},synchronize_session=False)
session.commit()

result = session.query(Users).all()
for row in result:
        print(row.id,row.name)

result = session.query(Users).filter(Users.id >= 2)
for row in result:
        print(row.id,row.name)

result = session.query(Users).filter(Users.id >= 2).first()
print(result)
 
 

############################## 其他常用 ###############################

指定列

select id,name as cname from users;
result = session.query(Users.id,Users.name.label('cname')).all()
for item in result:
        print(item[0],item.id,item.cname)

默认条件and

session.query(Users).filter(Users.id > 1, Users.name == 'eric').all()

between 之间查询

session.query(Users).filter(Users.id.between(1, 3), Users.name == 'eric').all()

in

 session.query(Users).filter(Users.id.in_([1,3,4])).all()
 session.query(Users).filter(~Users.id.in_([1,3,4])).all()

子查询

session.query(Users).filter(Users.id.in_(session.query(Users.id).filter(Users.name=='eric'))).all()

and 和 or

from sqlalchemy import and_, or_
session.query(Users).filter(Users.id > 3, Users.name == 'eric').all()
session.query(Users).filter(and_(Users.id > 3, Users.name == 'eric')).all()
session.query(Users).filter(or_(Users.id < 2, Users.name == 'eric')).all()
session.query(Users).filter(
    or_(
        Users.id < 2,
        and_(Users.name == 'eric', Users.id > 3),
        Users.extra != ""
    )).all()

filter_by  写参数

session.query(Users).filter_by(name='alex').all()

通配符

ret = session.query(Users).filter(Users.name.like('e%')).all()
ret = session.query(Users).filter(~Users.name.like('e%')).all()   # ~ 是 not 

切片

result = 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()

group by  分组

from sqlalchemy.sql import func

ret = session.query(
        Users.depart_id,
        func.count(Users.id),
).group_by(Users.depart_id).all()
for item in ret:
        print(item)

from sqlalchemy.sql import func

ret = session.query(
        Users.depart_id,
        func.count(Users.id),
).group_by(Users.depart_id).having(func.count(Users.id) >= 2).all()
for item in ret:
        print(item)

union 和 union all

"""
组合:
select id,name from users
UNION    #去重组合  不去重union all
select id,name from users;
"""
# 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()

 

posted @ 2018-06-20 16:22  PythonAV  阅读(1748)  评论(0编辑  收藏  举报