Sling Academy
Home/SQLAlchemy/SQLAlchemy: How to Update a Record by ID

SQLAlchemy: How to Update a Record by ID

Last updated: January 04, 2024

Introduction

SQLAlchemy is a powerful ORM library for Python that facilitates the interaction with databases through SQL without directly writing SQL queries. In this guide, we will explore how SQLAlchemy can be used to update records in a database by their identifying numbers, known as IDs.

Setting Up the Environment

Ensure you have SQLAlchemy installed in your Python environment. You can install it using pip:

pip install SQLAlchemy

We’ll also need a database to work with. For this tutorial, we’ll use SQLite, which is supported out of the box by SQLAlchemy and doesn’t require any additional setup.

Defining Models

Let’s start with defining a simple model for our tutorial. We will use the declarative approach provided by SQLAlchemy:

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

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

# Create SQLite engine
engine = create_engine('sqlite:///mydatabase.db')
Base.metadata.create_all(engine)

# Create Session
Session = sessionmaker(bind=engine)

Inserting Records

Before we update a record, we need to have one to update. Let’s add a user:

session = Session()
new_user = User(name='John Doe', age=30)
session.add(new_user)
session.commit()

Updating a Record by ID

Now that we have a record, let’s update the user’s age by their ID:

user_to_update = session.query(User).get(1)
if user_to_update:
    user_to_update.age = 31
    session.commit()

This code retrieves the user with ID 1 and, if such a user exists, updates their age and commits the changes to the database.

Advanced Usage

Consider a situation where we want to update multiple fields or only update a record if it meets certain conditions:

user_to_update = session.query(User).filter_by(id=1).first()
if user_to_update:
    user_to_update.name = 'Jane Doe'
    user_to_update.age = 32
    session.commit()

We’re using filter_by instead of get here for a more robust solution that can handle complex conditions.

Batch Updates

SQLAlchemy also allows batch updates. This is useful when you need to update multiple records at once:

session.query(User).filter(User.age < 30).update({'age': User.age + 1})
session.commit()

This will increment the age of all users below 30 by 1.

Using Synchronize Session

When working with batch updates, it’s important to keep the objects in-memory in sync with the database. Let’s see an example using synchronize_session:

session.query(User).filter(User.age < 30).update({'age': User.age + 1}, synchronize_session=False)
session.commit()

Setting synchronize_session to False may improve performance but requires caution.

Error Handling

While updating records, errors can occur. We should always be prepared to handle them:

try:
    user_to_update = session.query(User).get(1)
    if user_to_update:
        user_to_update.age = 31
        session.commit()
except Exception as e:
    print('An error occurred:', e)
    session.rollback()

By catching exceptions, we can rollback any uncommitted changes if an update fails.

Conclusion

In this guide, we’ve gone through the basic to advanced usage of updating records in SQLAlchemy by ID. Remember, proper testing and exception handling are crucial when dealing with database operations to ensure data integrity and avoid unexpected failures.

Next Article: SQLAlchemy: How to Delete a Record by ID

Previous Article: SQLAlchemy: How to Bulk Insert Data into a Table

Series: SQLAlchemy Tutorials: From Basic to Advanced

SQLAlchemy

You May Also Like

  • SQLAlchemy: Counting rows for each category (2 approaches)
  • SQLAlchemy: Adding a calculated column to SELECT query
  • SQLAlchemy: Grouping data on multiple columns
  • SQLAlchemy: How to temporarily delete a row
  • SQLAlchemy Composite Indexes: The Complete Guide
  • Full-Text Search in SQLAlchemy: The Ultimate Guide
  • SQLAlchemy: What if you don’t close database connections?
  • SQLAlchemy: How to Remove FOREIGN KEY Constraints (2 Ways)
  • SQLAlchemy: How to Create and Use Temporary Tables
  • SQLAlchemy: Saving Categories and Subcategories in the Same Table
  • SQLAlchemy: How to Automatically Delete Old Records
  • Weighted Random Selection in SQLAlchemy: An In-Depth Guide
  • SQLAlchemy: created_at and updated_at columns
  • How to Use Regular Expressions in SQLAlchemy
  • SQLAlchemy: Ways to Find Results by a Keyword
  • SQLAlchemy: How to Connect to MySQL Database
  • SQLAlchemy: How to Bulk Insert Data into a Table
  • SQLAlchemy: Singular vs Plural Table Names
  • SQLAlchemy: How to Add/Remove a Primary Key Constraint