[파이썬] SQLAlchemy 데이터 조회 (SELECT)

In this blog post, we will explore how to perform data SELECT operations using SQLAlchemy in Python.

To get started, make sure you have SQLAlchemy installed in your Python environment. You can install it using pip:

pip install sqlalchemy

Once you have SQLAlchemy installed, you can begin by importing the necessary modules:

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

Next, establish a connection to your database using the create_engine function, which takes the connection string as an argument. For example, if you are using MySQL, you can connect like this:

engine = create_engine('mysql+mysqlconnector://user:password@localhost/database')

Now, create a Session object using the sessionmaker function and bind it to the engine:

Session = sessionmaker(bind=engine)
session = Session()

With the session object, you can now execute SELECT queries. For instance, if you have a table named users with columns id, name, and email, you can perform a simple SELECT query like this:

from sqlalchemy import text

result = session.query(User).filter(text("name = 'John'")).all()

In the above code, we are querying the User table and filtering the results based on the condition name = 'John'. The all() method returns all the matching rows as a list.

You can also retrieve only specific columns by using the .values method:

result = session.query(User.name, User.email).all()

In this case, the result variable will contain a list of tuples, where each tuple represents a row with the selected columns.

Additionally, you can perform more advanced filtering, ordering, joining, and aggregating operations using the various methods provided by SQLAlchemy.

Remember to close the session once you are done with your queries:

session.close()

This is a basic introduction to performing data SELECT operations using SQLAlchemy in Python. It provides a convenient and flexible way to interact with databases using an object-oriented approach.

SQLAlchemy offers many advanced features and can be used with various database management systems. To learn more, refer to the official SQLAlchemy documentation: https://docs.sqlalchemy.org/.

Happy coding! 😊