[파이썬] SQLAlchemy 데이터 업데이트 (UPDATE)

SQLAlchemy is a powerful and popular SQL toolkit and Object-Relational Mapping (ORM) library for Python. It provides a simple and intuitive way to interact with databases using Python code.

In this blog post, we will focus on how to update data using SQLAlchemy in Python. Updating data in a database is a common operation when working with persistent data, and SQLAlchemy provides a convenient and efficient way to perform updates.

Updating Data using SQLAlchemy

To update data in a database using SQLAlchemy, we need to follow these steps:

  1. Import the necessary modules from SQLAlchemy.
  2. Establish a connection to the database.
  3. Define the table model or class using SQLAlchemy’s declarative_base().
  4. Create an instance of the table model and assign it to a variable.
  5. Start a session using the sessionmaker class.
  6. Use the session to query the database and update the desired data.
  7. Commit the changes to the database.
  8. Close the session and the database connection.

Let’s see an example of how to update data using SQLAlchemy in Python.

# Step 1: Import necessary modules
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

# Step 2: Establish a connection to the database
engine = create_engine('sqlite:///mydatabase.db')

# Step 3: Define the table model or class
Base = declarative_base()

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

# Step 4: Create an instance of the table model
user = User()

# Step 5: Start a session
Session = sessionmaker(bind=engine)
session = Session()

# Step 6: Update the data
user_to_update = session.query(User).filter_by(id=1).first()
user_to_update.name = 'John Doe'
user_to_update.age = 30

# Step 7: Commit the changes
session.commit()

# Step 8: Close the session and connection
session.close()

In the above example, we first import the necessary modules from SQLAlchemy. Then we establish a connection to the database using create_engine function.

Next, we define the table model or class using SQLAlchemy’s declarative_base() function. We create an instance of the table model and assign it to a variable.

After that, we start a session using the sessionmaker class and use it to query the database and update the desired data. In this example, we update the name and age of a specific user with id=1.

Finally, we commit the changes to the database, close the session, and close the database connection.

Updating data using SQLAlchemy is straightforward and allows you to easily modify the data in your database. SQLAlchemy provides a clean and powerful interface for interacting with databases in Python, making it a great choice for data manipulation tasks.