新增模型物件操作

yongheng999發表於2024-07-09

對模型物件進行新增,有兩種方式:

<!--第一種:類SQL方式-->
insert_stmt = insert(User).values(name='name1')
with Session() as sess:
sess.execute(insert_stmt)
sess.commit()
<!--未繫結引數-->
insert_stmt2 = insert(User)
with Session() as sess:
sess.execute(insert_stmt2,{'name':'name1'})
sess.commit()
<!--批次-->
with Session() as sess:
sess.execute(insert_stmt2,[{'name':'name1'},{'name':'name2'}])
sess.commit()
<!--第二種: 物件導向方式-->
obj=User(name='name2')
with Session() as sess:
sess.add(obj)
sess.commit()
<!--批次-->
obj=User(name='name2')
obj2=User(name='name2')
with Session() as sess:
sess.add(obj)
sess.add(obj2)
# 或者 s.add_all([obj,obj2])
sess.commit()
# 批次新增物件
with sessionmaker(engine).begin() as session:
emp1 = Employee(name='zs', sal=2000, bonus=500, gender=SexValue.MALE)
emp2 = Employee(name='ls', sal=3000, bonus=400, gender=SexValue.MALE)
session.add_all((emp1, emp2))

相關文章