软件测试|测试平台后端开发 Flask 操作数据库 - 数据 CRUD(增删改查)
作者:霍格沃兹测试开发学社
- 2023-09-07 北京
本文字数:1376 字
阅读完需:约 5 分钟
添加数据(create)
单条数据添加:
if __name__ == '__main__': """ 1. 实例化类,创建表数据 2. 将实例添加到 session(add) 3. 提交更新 (commit) 4. 关闭 session """ user = User(username="hogwarts", email="1254236457@qq.com") # 将数据提交到session with app.app_context(): db.session.add(user) # 将数据提交到commit db.session.commit() # 关闭 session db.session.close()
复制代码
批量数据添加:
""" 多条数据添加 1. 多次实例化类,创建多条表数据 2. 将多个实例依次添加到 session(add)中或者一次性添加到 session 中(add_all) 3. 提交更新 (commit) 4. 关闭 session """ user2 = User(username="joker", email="125@qq.com") user3 = User(username="joker4234", email="125wery@qq.com") # 将数据提交到session with app.app_context(): # 第一种,依次添加 # db.session.add(user2) # db.session.add(user3) # 第二种,批量添加,add_all需要传入一个列表,列表中存放数据对象 db.session.add_all([user2,user3]) # 将数据提交到commit db.session.commit() # 关闭 session db.session.close()
复制代码
读取数据(read)
查询表中所有数据:
类名.query.all()
# 读取全部数据 with app.app_context(): res = User.query.all() for r in res: print(r.username, r.email)
复制代码
查询条件:
单条数据:类名.query.filter_by(条件).first()
多条数据:类名.query.filter_by(条件).all()
# 查询多条数据 with app.app_context(): res = User.query.filter_by(age=20).all() for r in res: print(r.username, r.email) # 查询单条数据 with app.app_context(): res = User.query.filter_by(age=20).first() print(res.username, res.email)
复制代码
如果有多个查询条件,直接在后面用 filter_by 方法添加查询条件即可
修改数据(update)
"""方法一:1. 首先查询出来需要的数据2. 对查询出来的数据对象进行属性修改3. 提交session"""with app.app_context(): res = User.query.filter_by(age=21).first() res.username = "霍格沃兹" db.session.commit() db.session.close()"""方法二:给定查询条件查询后,直接用update()方法进行修改提交session"""with app.app_context(): res = User.query.filter_by(age=21).update({'email': "1245@qq.com"}) db.session.commit() db.session.close()
复制代码
删除数据(delete)
"""方法一:1. 首先查询出来需要的数据2. 对查询出来的数据对象进行属性修改3. 提交session"""with app.app_context(): res = User.query.filter_by(age=21).first() res.username = "霍格沃兹" db.session.commit() db.session.close()"""方法二:给定查询条件查询后,直接用update()方法进行修改提交session"""with app.app_context(): res = User.query.filter_by(age=21).update({'email': "1245@qq.com"}) db.session.commit() db.session.close()
复制代码
获取更多技术资料,请点击!
划线
评论
复制
发布于: 刚刚阅读数: 5
霍格沃兹测试开发学社
关注
社区:ceshiren.com 微信:ceshiren2021 2019-10-23 加入
微信公众号:霍格沃兹测试开发 提供性能测试、自动化测试、测试开发等资料,实时更新一线互联网大厂测试岗位内推需求,共享测试行业动态及资讯,更可零距离接触众多业内大佬。










评论