1,知识拾遗-SQLAlchemy基本操作-增删改查-外键

SQLAlchemy

 

pip3 install sqlalchemy

 

 

sqlalchemy生成model文件 sqlalchemy add_sqlalchemy

 

1,单表操作

sqlalchemy生成model文件 sqlalchemy add_数据_02

sqlalchemy生成model文件 sqlalchemy add_sqlalchemy_03

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String

#创建基类,相当于Django中的 models.Model,被各个数据表类所继承
Base = declarative_base()


# ##################### 单表示例 #########################
# 创建一张数据表
class Users(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String(32), index=True)

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

# 创建另一张数据表
class School(Base):
    __tablename__ = "school"

    id = Column(Integer,primary_key=True,autoincrement=True)
    name = Column(String,unique=True)


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


# 通过Base.metadata找到所有继承 Base 的数据表class
Base.metadata.create_all(engine)

# SQLAlchemy数据表进行修改后,无法直接进行更新,只能删除表后进行操作,重新进行操作

创建基类和第一张数据表

创建-注意用户名跟密码

 

 

 

2,增删改查

from s1 import Users,School

# 1. 创建一个用户添加到数据库
# 创建连接
from sqlalchemy import create_engine
engine = create_engine("mysql+pymysql://root:root@localhost:3306/s13lastweek?charset=utf8")

# 创建数据表操作对象 sessionmaker
from sqlalchemy.orm import sessionmaker
DB_session = sessionmaker(engine)
db_session = DB_session()

# 1.增加 操作数据表
# 单行操作
# user = Users(name="123") # 通过 Users数据表类创建一条数据
# db_session.add(user) # 将创建好的数据添加到 数据表操作对象的内存中,此时数据库还并不知道要添加数据
# db_session.commit() # 将数据表操作对象内存中的所有数据及操作提交到数据库中
# 多行操作
# db_session.add_all([
#     Users(name="jwb"),
#     Users(name="ywb"),
# ])
# db_session.commit()

# 2.查询 数据表操作
# user_list = db_session.query(Users).all() # 查询所有数据
# user_one = db_session.query(Users).first() # 查询第一条数据
# print(user_list.id,user_list.name)
# for row in user_list:
#     print(row.id,row.name)
# user_list = db_session.query(Users).filter(Users.id >=2) # 查询带有条件的数据 表达式 返回sql语句,循环依然可以获取到数据
# print(user_list,type(user_list))
# for row in user_list:
#     print(row.id,row.name)
# user_list = db_session.query(Users).filter(Users.id >=2).all() # 查询带有条件的数据 表达式 返回数据列表
# print(user_list)
# for row in user_list:
#     print(row.id,row.name)

# 3.删除数据 数据表操作
# db_session.query(Users).filter(Users.id == 1).delete() # 删除带有条件的数据
# db_session.commit()

# 4.修改
db_session.query(Users).filter(Users.id == 3).update({"name":"dawangba"}) # 更新id=3的数据
db_session.commit()

# 关闭连接
db_session.close()

 

//

高级版增删改查

from s1 import Users,School

# 1. 创建一个用户添加到数据库
# 创建连接
from sqlalchemy import create_engine
engine = create_engine("mysql+pymysql://root:root@localhost:3306/s13lastweek?charset=utf8")

# 创建数据表操作对象 sessionmaker
from sqlalchemy.orm import sessionmaker
DB_session = sessionmaker(engine)
db_session = DB_session()

# 1.增加 操作数据表

# 2.查询 数据表操作
# 查询数据表操作
"""
r1 = session.query(Users).all()
r2 = session.query(Users.name.label('xx'), Users.age).all()
r3 = session.query(Users).filter(Users.name == "alex").all()
r4 = session.query(Users).filter_by(name='alex').all()
r5 = session.query(Users).filter_by(name='alex').first()
r6 = session.query(Users).filter(text("id<:value and name=:name")).params(value=224, name='fred').order_by(Users.id).all()
r7 = session.query(Users).from_statement(text("SELECT * FROM users where name=:name")).params(name='ed').all()
"""
# 筛选查询列
# user_list = db_session.query(Users.name).all()
# print(user_list) # [('alexDSB',), ('zhangsan',)] 虽然看到的是元祖,但是依然可以通过对象打点儿调用属性
# for row in user_list:
#     print(row.name)

# 别名映射  name as nick
# """
# select name as nick  from users
# """
# user_list = db_session.query(Users.name.label("nick")).all()
# print(user_list) # [('alexDSB',), ('zhangsan',)] 虽然看到的是元祖,但是依然可以通过对象打点儿调用属性
# for row in user_list:
#     print(row.nick) # 这里要写别名了

# 筛选条件格式
# user_list = db_session.query(Users).filter(Users.name == "alexDSB").all()
# user_list = db_session.query(Users).filter(Users.name == "alexDSB").first()
# user_list = db_session.query(Users).filter_by(name="dawangba").first() # where name="dawangba"
# print(user_list.name)
# for row in user_list:
#     print(row.name)

# 复杂查询
# from sqlalchemy.sql import text
# user_list = db_session.query(Users).filter(text("id<:id and name=:name")).params(id=4,name="dawangba").all()
# print(user_list)

# 查询语句
# from sqlalchemy.sql import text
# user_list = db_session.query(Users).filter(text("select *  from users where id<:id and name=:name")).params(id=4,name='dawangba').all()
# print(user_list)

# 排序 :
# user_list = db_session.query(Users).order_by(Users.id.asc()).all()
# user_list = db_session.query(Users).order_by(Users.id.desc()).all()
# for row in user_list:
#     print(row.name,row.id)

#其他查询条件
"""
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() # between 大于1小于3的
ret = session.query(Users).filter(Users.id.in_([1,3,4])).all() # in_([1,3,4]) 只查询id等于1,3,4的
ret = session.query(Users).filter(~Users.id.in_([1,3,4])).all() # ~xxxx.in_([1,3,4]) 查询不等于1,3,4的
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()
# select * from users where id<2 or (name="eric" and id>3) or extra != "" 

 or or (name="eric" and id>3)

or_(id < 2 ,extra != "" ,and_(name="eric" , id>3) )

"""

# 2修改 :
"""
db_session.query(Users).filter(Users.id > 0).update({"name" : "099"})
db_session.query(Users).filter(Users.id > 0).update({Users.name: Users.name + "099"}, synchronize_session=False)  #注意不同模式对应后面的False或者evaluate
db_session.query(Users).filter(Users.id > 0).update({"age": Users.age + 1}, synchronize_session="evaluate")
db_session.commit()
"""
# db_session.query(Users).filter(Users.name == "dawangba").update({Users.name: Users.name + "999"}, synchronize_session=False)
# db_session.query(Users).filter(Users.name == "dawangba999").update({"name": "dawangba"}, synchronize_session="evaluate")
# db_session.commit()

# 关闭连接
db_session.close()

//

 

 

 

//

 

 

 

//