[파이썬] SQLAlchemy SQL Expression Language 활용

SQLAlchemy is a powerful and popular Python library used for working with databases. It provides a SQL Expression Language that allows developers to express database queries and manipulations using Python syntax rather than writing raw SQL statements. This makes working with databases easier, more readable, and less error-prone.

In this blog post, we will explore how to leverage the SQLAlchemy SQL Expression Language to perform common database operations such as querying, filtering, inserting, updating, and deleting data.

Connecting to the Database

Before we can start using SQLAlchemy, we need to establish a connection to the database. Here’s an example of connecting to a SQLite database:

from sqlalchemy import create_engine

engine = create_engine('sqlite:///mydatabase.db')
connection = engine.connect()

Querying Data

To query data from the database, we can use the select() function from the SQLAlchemy SQL Expression Language. Here’s an example of selecting all records from a table named “users”:

from sqlalchemy import select
from sqlalchemy.sql import text

query = select('*').select_from(text('users'))
result_proxy = connection.execute(query)
results = result_proxy.fetchall()

for row in results:
    print(row)

You can also apply filters to the query using the where() function. Here’s an example of selecting users with a specific age:

query = select('*').select_from(text('users')).where(text('age = :age')).params(age=25)
result_proxy = connection.execute(query)
results = result_proxy.fetchall()

for row in results:
    print(row)

Inserting Data

To insert data into a database table, we can use the insert() function. Here’s an example of inserting a new user into the “users” table:

from sqlalchemy import insert

query = insert(text('users')).values(name='John Doe', age=30)
connection.execute(query)

Updating Data

To update existing data in a database table, we can use the update() function. Here’s an example of updating the age of a user with a specific name:

from sqlalchemy import update

query = update(text('users')).where(text('name = :name')).values(age=35).params(name='John Doe')
connection.execute(query)

Deleting Data

To delete data from a database table, we can use the delete() function. Here’s an example of deleting a user with a specific email address:

from sqlalchemy import delete

query = delete(text('users')).where(text('email = :email')).params(email='john@example.com')
connection.execute(query)

Conclusion

The SQLAlchemy SQL Expression Language provides a convenient and powerful way to work with databases using Python. By leveraging SQLAlchemy’s expressive syntax, developers can write more readable and maintainable code for database operations. In this blog post, we covered querying, filtering, inserting, updating, and deleting data using SQLAlchemy.