How to use SQLAlchemy update in Python?

There are a few different ways to perform update operations in Python using SQLAlchemy. Here are some common methods for using SQLAlchemy:

Option 1: Utilize the update() method.

from sqlalchemy import create_engine, update
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

# 连接数据库
engine = create_engine('数据库连接字符串')
Session = sessionmaker(bind=engine)
session = Session()

# 定义映射类
Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    age = Column(Integer)

# 更新记录
stmt = update(User).where(User.id == 1).values(name='new_name')
session.execute(stmt)
session.commit()

Option 2: Utilize the update() method of the query object.

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

# 连接数据库
engine = create_engine('数据库连接字符串')
Session = sessionmaker(bind=engine)
session = Session()

# 定义映射类
Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    age = Column(Integer)

# 更新记录
session.query(User).filter(User.id == 1).update({User.name: 'new_name'})
session.commit()

Option:
Method 3: Execute native SQL statements using the execute() method.

from sqlalchemy import create_engine

# 连接数据库
engine = create_engine('数据库连接字符串')

# 更新记录
with engine.connect() as connection:
    connection.execute("UPDATE users SET name='new_name' WHERE id = 1")

Here are several common methods for performing updates using SQLAlchemy. Choose the method that best fits your specific situation for updating data.

bannerAds