Junior — Middle
What methods of database interaction are you familiar with when using SQLAlchemy?
sobes.tech AI
Answer from AI
When working with SQLAlchemy in Python, the following methods of interacting with the database are known:
-
Using ORM (Object-Relational Mapping):
- Creating and manipulating model objects that correspond to database tables.
- Adding (
session.add()), updating, deleting objects. - Queries through
session.query()with filters, sorting, and joins.
-
Using Core API:
- Creating and executing SQL queries via
Table,select(),insert(),update(),delete()objects. - Allows writing more low-level and flexible code.
- Creating and executing SQL queries via
-
Working with sessions:
- Managing transactions through
session.commit(),session.rollback().
- Managing transactions through
-
Executing raw SQL queries:
- Using
engine.execute()orsession.execute()to run arbitrary SQL queries.
- Using
Example of a simple ORM query:
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
session = Session()
users = session.query(User).filter(User.age > 18).all()
for user in users:
print(user.name)
SQLAlchemy provides a powerful and flexible set of tools for working with databases both at the object level and at the SQL level.