LambdaQueryWrapper 更新数据
时间: 2023-12-06 18:38:47 浏览: 92
LambdaQueryWrapper可以用于更新数据,具体操作如下所示:
```python
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from sqlalchemy.sql.expression import LambdaElement
from sqlalchemy import update
from sqlalchemy.orm import aliased
from sqlalchemy.orm import Query
from sqlalchemy.orm import Session
from sqlalchemy import and_
# 创建数据库连接
engine = create_engine('mysql+pymysql://username:password@host:port/database_name')
# 创建会话
Session = sessionmaker(bind=engine)
session = Session()
# 创建基类
Base = declarative_base()
# 定义数据表
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
name = Column(String(50))
age = Column(Integer)
# 更新数据
session.query(User).filter(User.id == 1).update({User.age: 20})
# 使用LambdaQueryWrapper更新数据
from sqlalchemy.orm import aliased
from sqlalchemy import and_
# 创建别名
u1 = aliased(User)
u2 = aliased(User)
# 构造查询条件
condition = and_(u1.id == u2.id, u1.age > 18, u2.age < 30)
# 构造更新数据
data = {User.age: 20}
# 构造更新语句
update_stmt = (
session.query(User)
.filter(condition)
.update(data, synchronize_session=False)
)
# 提交事务
session.commit()
```
阅读全文