SQLAlchemy增删改查 一对多 多对多

今天来聊一聊Python的ORM框架SQLAlchemy 有些同学已经听说过这个框架的大名了,也听说了SQLAlchemy没有Django的Models好用

1 创建数据表

create_table.py

# 1 导入基础模型
from sqlalchemy.ext.declarative import declarative_base

#2 创建ORM模型基类  实例化模型
Base = declarative_base()

#3 导入ORM对应数据库数据类型的字段
from sqlalchemy import Column,Integer,String

#4 创建ORM对象   # 当前的这个Object继承了Base也就是代表了Object继承了ORM的模型
class User(Base):   # 相当于 Django Models中的 Model
    # 为Table创建名称
    __tablename__ = "user"
    id = Column(Integer,primary_key=True,autoincrement=True)
    name = Column(String(32),index = True)

# 5 创建数据库连接
from sqlalchemy import create_engine
#注意 root后面的空白处填写密码
engine = create_engine("mysql+pymysql://root:@127.0.0.1:3306/sqla?charset=utf8")
#数据库连接创建完成



#6 去数据库中创建与User所对应的数据表
#去engine数据库中创建所有继承Base类的ORM对象     
# Base 自动检索所有继承Base的ORM 对象 并且创建所有的数据表 Base.metadata.create_all(engine)

 

2 增删改查操作

2.1 增加数据

#增加数据
#1 创建数据库连接
from create_table import engine

#2 创建会话 ---打开数据库连接

from sqlalchemy.orm import sessionmaker

#3 创建回话窗口
Session = sessionmaker(engine)

# 4打开回话窗口
db_session = Session()

#单条数据的增加
# #1 导入  首先导入之间做好的ORM 对象 User
# from create_table import User
#
# #2 增加数据 add只能放一个对象 而add_all 里面放一个列表 也就是多个对象
# user_obj = User(name='mlh')
# db_session.add(user_obj)  #相当于Insert into
#
# #3 执行会话中的所有操作
# db_session.commit()
#
# #4 关闭会话
# db_session.close()


#批量增加
# from create_table import User
#
# db_session.add_all({
#     User(name='猪猪'),
#     User(name='花花'),
#     User(name='乖乖'),
# })
#
# db_session.commit()
# db_session.close()


#扩展  db_session可同时执行多条语句
from create_table import User
user1 = User(name='lala')
user2 = User(name='dada')
user3 = User(name='tata')

db_session.add(user1)
db_session.add(user2)
db_session.add(user3)
#这里的知识点就是db_session支持多条语句同时执行
db_session.commit()
db_session.close()

 

 

2.2 查询数据

#查询数据
#会话窗口
from sqlalchemy.orm import sessionmaker
from create_table import engine
#1 创建窗口
Session = sessionmaker(engine)
#2 打开回话窗口
db_session = Session()

# 1 简单查询
# select * from table

from create_table import User
#查询出User表中的所有数据

#注意 要是后面没有.all()  则打印出来的是一个sql语句  将所有的数据序列化成
# user_sql = db_session.query(User)
# print(user_sql)   #结果是
                  #SELECT user.id AS user_id, user.name AS user_name
                  # FROM user

#注意.all()返回的是列表
# user_list = db_session.query(User).all()
# print(user_list) #这是一个列表
#
#
# for row in user_list:
#     print(row.id,row.name)
#6 dada
#5 lala
#1 mlh
#7 tata
#4 乖乖
#2 猪猪
#3 花花

#查询第一条数据
# user = db_session.query(User).first()
# print(user.id,user.name)



#带条件的查询
#方式一 filter
# user_a = db_session.query(User).filter(User.id == 4).all()
# print(user_a[0].id,user_a[0].name)


# 方式二 filter_by
# user_a = db_session.query(User).filter_by(id=4).first()
# print(user_a.id,user_a.name)

#
# user_list = db_session.query(User).filter(User.id >= 4).all()
# for row in user_list:
#     print(row.id,row.name)


#扩展 查看sql语句
user_sql = db_session.query(User).filter(User.id >= 4)
print(user_sql)

#结果是 SELECT user.id AS user_id, user.name AS user_name FROM user WHERE user.id >= %(id_1)s

 

2.3 修改数据

#更新修改数据
from create_table import engine,User
from sqlalchemy.orm import sessionmaker

# 1 创建会话窗口
Session = sessionmaker(engine)
# 2 打开会话窗口
db_session = Session()

#修改数据 (首先要查存出要修改的数据)
#sql语句  update 'user' set 'name' = '666' where id =1
# user_up = db_session.query(User).filter(User.name == "mlh").update({'name':'佩奇'})
# print(user_up)  #打印出来的是受影响的行数  为1
#
# db_session.commit()
# db_session.close()


# 符合条件 就修改  这里有多个
user_up = db_session.query(User).filter(User.id >= 5).update({'name':'小猪佩奇'})
print(user_up)  #打印出来的是受影响的行数  为3
db_session.commit()
db_session.close()



# commit 提交操作 除了查询 增加修改删除都要commit()操作

 

2.4 删除数据

from sqlalchemy.orm import sessionmaker
from create_table import engine,User

#1 创建会话窗口
Session = sessionmaker(engine)

#2 打开会话窗口
db_session = Session()


#删除操作  首先要查询出要删除的数据
#sql语句 delete from user where id=5
#删除一条数据
# user_del = db_session.query(User).filter(User.id==5).delete()
# print(user_del)
#
# db_session.commit()
# db_session.close()

#删除多条数据
# user_del = db_session.query(User).filter(User.id >= 5).delete()
# print(user_del)
# db_session.commit()
# db_session.close()

#

 

2.5 高级版查询操作

#老规矩
from create_table import User,engine
from sqlalchemy.orm import sessionmaker

Session = sessionmaker(engine)
db_session = Session()

# 查询数据表操作
# and or
from sqlalchemy.sql import and_ , or_
ret = db_session.query(User).filter(and_(User.id > 3, User.name == '乖乖')).all()
ret = db_session.query(User).filter(or_(User.id < 2, User.name == '乖乖')).all()

# 查询所有数据
r1 = db_session.query(User).all()

# 查询数据 指定查询数据列 加入别名
r2 = db_session.query(User.name.label('username'), User.id).first()
print(r2.id,r2.username) # 15 NBDragon

# 表达式筛选条件
r3 = db_session.query(User).filter(User.name == "乖乖").all()

# 原生SQL筛选条件
r4 = db_session.query(User).filter_by(name='乖乖').all()
r5 = db_session.query(User).filter_by(name='乖乖').first()

# 字符串匹配方式筛选条件 并使用 order_by进行排序
r6 = db_session.query(User).filter(text("id<:value and name=:name")).params(value=224, name='乖乖').order_by(User.id).all()

#原生SQL查询
r7 = db_session.query(User).from_statement(text("SELECT * FROM User where name=:name")).params(name='乖乖').all()

# 筛选查询列
# query的时候我们不在使用User ORM对象,而是使用User.name来对内容进行选取
user_list = db_session.query(User.name).all()
print(user_list)
for row in user_list:
    print(row.name)

# 别名映射  name as nick
user_list = db_session.query(User.name.label("nick")).all()
print(user_list)
for row in user_list:
    print(row.nick) # 这里要写别名了

# 筛选条件格式
user_list = db_session.query(User).filter(User.name == "乖乖").all()
user_list = db_session.query(User).filter(User.name == "乖乖").first()
user_list = db_session.query(User).filter_by(name="乖乖").first()
for row in user_list:
    print(row.nick)

# 复杂查询
from sqlalchemy.sql import text
user_list = db_session.query(User).filter(text("id<:value and name=:name")).params(value=3,name="乖乖")

# 查询语句
from sqlalchemy.sql import text
user_list = db_session.query(User).filter(text("select * from User id<:value and name=:name")).params(value=3,name="乖乖")

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

#其他查询条件
"""
ret = session.query(User).filter_by(name='乖乖').all()
ret = session.query(User).filter(User.id > 1, User.name == '乖乖').all()
ret = session.query(User).filter(User.id.between(1, 3), User.name == '乖乖').all() # between 大于1小于3的
ret = session.query(User).filter(User.id.in_([1,3,4])).all() # in_([1,3,4]) 只查询id等于1,3,4的
ret = session.query(User).filter(~User.id.in_([1,3,4])).all() # ~xxxx.in_([1,3,4]) 查询不等于1,3,4的
ret = session.query(User).filter(User.id.in_(session.query(User.id).filter_by(name='乖乖'))).all() 子查询
from sqlalchemy import and_, or_
ret = session.query(User).filter(and_(User.id > 3, User.name == '乖乖')).all()
ret = session.query(User).filter(or_(User.id < 2, User.name == '乖乖')).all()
ret = session.query(User).filter(
    or_(
        User.id < 2,
        and_(User.name == 'eric', User.id > 3),
        User.extra != ""
    )).all()
# select * from User where id<2 or (name="eric" and id>3) or extra != "" 

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

# 限制
ret = db_session.query(User)[1:2]

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

# 分组
from sqlalchemy.sql import func

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

ret = db_session.query(
    func.max(User.id),
    func.sum(User.id),
    func.min(User.id)).group_by(User.name).having(func.min(User.id) >2).all()
"""

# 关闭连接
db_session.close()

orm_select_more

 

2.6 高级修改数据操作

#高级版更新操作
from create_table import User,engine
from sqlalchemy.orm import sessionmaker

Session = sessionmaker(engine)
db_session = Session()

#直接修改
db_session.query(User).filter(User.id > 0).update({"name" : "099"})

#在原有值基础上添加 - 1
db_session.query(User).filter(User.id > 0).update({User.name: User.name + "099"}, synchronize_session=False)

#在原有值基础上添加 - 2
db_session.query(User).filter(User.id > 0).update({"age": User.age + 1}, synchronize_session="evaluate")
db_session.commit()

orm_update_more

 

3 一对多的操作:ForeignKey

3.1 创建数据表及其关系relationship:

create_table_ForeignKey.py

#一对多建表操作

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

from sqlalchemy import Column,Integer,String,ForeignKey
from sqlalchemy.orm import relationship

class Student(Base):
    __tablename__ = "student"
    id = Column(Integer,primary_key=True,autoincrement=True)
    name = Column(String(32))
    school_id = Column(Integer,ForeignKey("school.id"))

    stu2sch = relationship("School",backref="sch2stu")




class School(Base):
    __tablename__ = "school"
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(32))


from sqlalchemy import create_engine
engine = create_engine("mysql+pymysql://root:@127.0.0.1:3306/sqla?charset=utf8")

Base.metadata.create_all(engine)

 3.2 基于relationship增加数据

from sqlalchemy.orm import sessionmaker
from create_table_ForeignKey import engine,Student,School

#1 创建会话窗口
Session = sessionmaker(engine)

#2 打开会话窗口
db_session = Session()

# 3增加操作  添加数据
# sch_obj = School(name="oldboybeijing")
# db_session.add(sch_obj)
# db_session.commit()

#然后查询出刚刚添加的学校信息 在这个学校中添加相应的学生信息
# sch = db_session.query(School).filter(School.name=="oldboybeijing").first()
# stu_obj = Student(name='猪猪',school_id=sch.id)
# db_session.add(stu_obj)
# db_session.commit()
# db_session.close()

#2 正向添加数据
stu_obj = Student(name='哒哒',stu2sch=School(name='oldboyshengzheng'))
db_session.add(stu_obj)
db_session.commit()
db_session.close()


#3 添加数据relationship版  反向添加
# sch_obj = School(name='oldboyshanghai')
# sch_obj.sch2stu = [Student(name='乖乖'),Student(name='哈哈')]
# db_session.add(sch_obj)
# db_session.commit()
# db_session.close()

 

 

3.3 基于relationship查询数据

from sqlalchemy.orm import sessionmaker
from create_table_ForeignKey import engine,Student,School

#1 创建会话窗口
Session = sessionmaker(engine)

#2 打开会话窗口
db_session = Session()


#查询数据 relationship版 正向查询数据
stu_obj = db_session.query(Student).all()
print(stu_obj)

for row in stu_obj:
    print(row.id,row.name,row.school_id,row.stu2sch.name)




# 反向查询数据
sch_obj = db_session.query(School).all()
for school in sch_obj:
    for student in school.sch2stu:
        print(school.id,school.name,student.name)

 

3.4 修改数据

from sqlalchemy.orm import sessionmaker
from create_table_ForeignKey import engine,Student,School

#1 创建会话窗口
Session = sessionmaker(engine)

#2 打开会话窗口
db_session = Session()

# 修改数据
sch = db_session.query(School).filter(School.name=="oldboyshanghai").first()
db_session.query(Student).filter(Student.name=='哒哒').update({'school_id':sch.id})
db_session.commit()
db_session.close()

 

3.5 删除数据

from sqlalchemy.orm import sessionmaker
from create_table_ForeignKey import engine,Student,School

#1 创建会话窗口
Session = sessionmaker(engine)

#2 打开会话窗口
db_session = Session()

#删除数据

sch = db_session.query(School).filter(School.name=='oldboyshanghai').first()
db_session.query(Student).filter(Student.school_id == sch.id).delete()
db_session.commit()
db_session.close()

 

4 多对多:ManyToMany

4.1创建表基关系

create_table_many.py

from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

from sqlalchemy.orm import relationship
from sqlalchemy import Column,Integer,String,ForeignKey


class Hotel(Base):
    __tablename__ ="hotel"
    id = Column(Integer,primary_key=True)
    girl_id =Column(Integer,ForeignKey('girl.id'))
    boy_id =Column(Integer,ForeignKey('boy.id'))


class Girl(Base):
    __tablename__ = "girl"
    id =Column(Integer,primary_key=True)
    name= Column(String(32),index=True)
    #创建关系   
    boys = relationship("Boy",secondary ="hotel",backref = "girl2boy")


class Boy(Base):
    __tablename__="boy"
    id = Column(Integer,primary_key = True)
    name = Column(String(32),index=True)



from sqlalchemy import create_engine
engine = create_engine("mysql+pymysql://root@127.0.0.1:3306/sqla?charset=utf8")

Base.metadata.create_all(engine)

 

curd_insert_many.py

from create_table_many import engine,Hotel,Girl,Boy
from sqlalchemy.orm import sessionmaker

#1 创建窗口
Session = sessionmaker(engine)
db_session = Session()


# 1 通过Girl添加Boy和Hotel数据 正向查询
girl = Girl(name='姗姗')
girl.boys =[Boy(name='吖吖')]
db_session.commit()
db_session.close()



#2 通过Boy添加Girl数据   反向添加数据
boy = Boy(name="哈哈")
boy.girl2boy = [Girl(name="照照"),Girl(name="滴滴")]
db_session.add(boy)
db_session.commit()
db_session.close()

 

 

from create_table_many import engine,Boy,Girl,Hotel
from sqlalchemy.orm import sessionmaker

Session = sessionmaker(engine)
db_session = Session()

#1 查询数据
1.通过Boy查询约会过的所有Girl
hotel = db_session.query(Boy).all()
for row in hotel:
    for row2 in row.girl2boy:
        print(row.name,row2.name)

1.通过Girl查询约会过的所有Boy
hotel = db_session.query(Girl).all()
for row in hotel:
    for row2 in row.boys:
        print(row.name,row2.name)
        

 

posted @ 2019-02-18 16:01  茉莉花M  阅读(504)  评论(0编辑  收藏  举报