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:
- Establish a connection to the database.
- Execute queries (SELECT, INSERT, UPDATE, DELETE) via ORM or SQL.
- Process the results.
- 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.