Sobes.tech
Junior — Middle

What is the main purpose of using ORM queries in applications?

sobes.tech AI

Answer from AI

The main goal of using ORM (Object-Relational Mapping) in applications is to simplify interaction with the database, allowing working with data as objects of the programming language rather than writing complex SQL queries manually. ORM automatically converts operations with objects into SQL queries and back, which improves code readability, reduces the likelihood of errors, and speeds up development.

Example using SQLAlchemy in Python:

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)

engine = create_engine('sqlite:///:memory:')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()

# Creating and adding a user
new_user = User(name='Alice')
session.add(new_user)
session.commit()

# Querying users
users = session.query(User).filter_by(name='Alice').all()
print(users)