对模型对象进行新增,有两种方式:
<!--第一种:类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))
标签:insert,sess,obj,name,对象,模型,新增,add,User From: https://www.cnblogs.com/yongheng999/p/18292307