Sobes.tech
Junior — Middle

How do you usually interact with the database in your work?

sobes.tech AI

Answer from AI

When working with a database in Python, I usually use an ORM (such as SQLAlchemy or Django ORM) for convenience and security, or directly through drivers (like psycopg2 for PostgreSQL).

Main steps:

  1. Establish a connection to the database.
  2. Execute queries (SELECT, INSERT, UPDATE, DELETE) via ORM or SQL.
  3. Process the results.
  4. Close the connection.

Example using SQLAlchemy:

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

engine = create_engine('postgresql://user:password@localhost/dbname')
Session = sessionmaker(bind=engine)
session = Session()

# example query
users = session.query(User).filter(User.age > 18).all()

for user in users:
    print(user.name)

session.commit()
session.close()

This approach simplifies working with the database and helps avoid errors related to SQL injections and transaction management.