[파이썬] SQLAlchemy Session-bound 연산

SQLAlchemy is a powerful and popular Object Relational Mapping (ORM) library for working with relational databases in Python. One of the key features of SQLAlchemy is its session management, which allows you to perform database operations within a specific session context.

In this blog post, we will explore how to perform SQLAlchemy session-bound operations in Python. Let’s dive right in!

Setting up the Database

First, let’s set up a connection to a database using SQLAlchemy. We’ll assume you already have a database created and will be using SQLite for this example.

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

# Create an engine to connect to the database
engine = create_engine('sqlite:///example.db')
Session = sessionmaker(bind=engine)
session = Session()

Here, we created an engine using create_engine() that specifies the database URL. We then created a Session class using sessionmaker() and bound it to the engine. Finally, we created a session object by calling the Session class.

Performing Session-bound Operations

Now that we have set up our session, let’s perform some session-bound operations. These operations allow us to execute database queries and modify the data within the session context.

Querying Data

To query data from the database within our session, we can use the query() method on the session object. Here’s an example:

# Query all users from the database
users = session.query(User).all()

# Print the user information
for user in users:
    print(user.username, user.email)

In this example, we use the query() method to select all users from the database. We then iterate over the result and print the username and email of each user.

Modifying Data

To modify the data within our session, we can use the session-bound methods such as add(), delete(), and commit().

# Create a new user
new_user = User(username='john', email='john@example.com')

# Add the new user to the session
session.add(new_user)

# Delete a user
user_to_delete = session.query(User).filter_by(username='jane').first()
if user_to_delete:
    session.delete(user_to_delete)

# Commit the changes
session.commit()

In this example, we create a new user object and add it to the session using the add() method. We also delete a user from the session using the delete() method. Finally, we call the commit() method to save the changes to the database.

Handling Transactions

Sessions in SQLAlchemy also provide transaction management. By default, each session begins a new transaction when it is created.

# Start a transaction explicitly
session.begin()

try:
    # Perform database operations
    # ...

    # Commit the transaction
    session.commit()
except:
    # Rollback the transaction on error
    session.rollback()
    raise

In this example, we explicitly start a transaction using the begin() method, perform some database operations, and then either commit or rollback the transaction based on the outcome.

Conclusion

SQLAlchemy’s session-bound operations provide a powerful and convenient way to work with relational databases in Python. Sessions allow you to query and modify data in a transactional manner, making it easier to maintain data consistency and integrity.

In this blog post, we explored how to set up a session and perform session-bound operations in SQLAlchemy. We covered querying data, modifying data, and handling transactions.

I hope you found this post helpful and feel more confident in working with SQLAlchemy sessions. Happy coding!