Sobes.tech
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:

  1. Direct use of drivers — for example, sqlite3 for SQLite, psycopg2 for PostgreSQL, mysql-connector-python for MySQL. Allows executing SQL queries directly.

  2. 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.

  3. Using high-level libraries — for example, Peewee, Tortoise ORM for 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.