添加数据(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()
浙公网安备 33010602011771号