欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Sqlalchemy - 数据的更新(*2)、删除

程序员文章站 2024-03-02 22:12:46
...

更新(.update({...})

  • 一般更新
from create_table import engine,User
from sqlalchemy.orm import sessionmaker

Session = sessionmaker(engine)
db_session = Session()


user_obj = db_session.query(User).filter(User.id == 179074001).update({"name":"XXX"})
db_session.commit()
  • 引用更新(在原有的数据基础上进行修改
from day0719.create_table import engine,Student
from sqlalchemy.orm import sessionmaker


Session = sessionmaker(engine)
db_session = Session()

# db_session.query(Student).update({"name":"Error"})
#res = db_session.query(Student).update({"student_id":Student.student_id + 10},synchronize_session="evaluate")

#因为是按照顺序进行增值,所以变化后的值不能够和其他一致(当为主键的时候)
res = db_session.query(Student).update({Student.student_id:Student.student_id + 10},synchronize_session=False)

print(res)
db_session.commit()


删除(.delete()):

from create_table import engine,User
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(engine)
db_session = Session()


# 删除数据(返回值为受影响行数)
user_object = db_session.query(User).filter(User.id == 179074001).delete()
print(user_object)
db_session.commit()

 

 

相关标签: sqlalchemy