Junior — Middle
What methods do you use for interacting with databases?
sobes.tech AI
Answer from AI
There are several approaches to interacting with databases in Python:
-
Direct use of drivers — for example,
sqlite3for SQLite,psycopg2for PostgreSQL,mysql-connector-pythonfor MySQL. Allows executing SQL queries directly. -
ORM (Object-Relational Mapping) — libraries like SQLAlchemy, Django ORM, enable working with the database through objects and classes, which simplifies the code and improves readability.
-
Using high-level libraries — for example,
Peewee,Tortoise ORMfor simpler projects.
An example using SQLAlchemy for data retrieval:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
engine = create_engine('sqlite:///example.db')
Session = sessionmaker(bind=engine)
session = Session()
# Assume there is a User model
users = session.query(User).filter(User.age > 18).all()
for user in users:
print(user.name)
Thus, the choice of method depends on the task, project complexity, and preferences.