前提条件
engine = create_engine("mysql+pymysql://root:root@127.0.0.1:3306/test", max_overflow=0, pool_size=5)
Session = sessionmaker(bind=engine)
session = Session()
增
obj1 = Users(name="wang")
session.add(obj1)
session.add_all([
Users(name="wang"),
Users(name="wei"),
])
session.commit()
删
session.query(Users).filter(Users.id > 1).delete()
session.commit()
改
session.query(Users).filter(Users.id > 0).update({"name" : "li"})
session.query(Users).filter(Users.id > 0).update({Users.name: Users.name + "li"}, synchronize_session=False)
session.query(Users).filter(Users.id > 0).update({"age": Users.age + 1}, synchronize_session="evaluate") # 数字相加,要'evaluate'
session.commit()
查
r1 = session.query(Users).all()
r2 = session.query(Users.name.label('xx'), Users.age).all() # label是取别名
r3 = session.query(Users).filter(Users.name == "alex").all()
r4 = session.query(Users).filter_by(name='alex').all()
r5 = session.query(Users).filter_by(name='alex').first()
r6 = session.query(Users).filter(text("id<:value and name=:name")).params(value=224, name='fred').order_by(Users.id).all()
r7 = session.query(Users).from_statement(text("SELECT * FROM users where name=:name")).params(name='ed').all()
close
session.close()