Middle
What is ORM? Pros and cons?
sobes.tech AI
Answer from AI
ORM (Object-Relational Mapping) is a technology that allows working with a database through objects in a programming language, abstracting SQL queries.
Advantages of ORM:
- Accelerates development as it reduces the need to write extensive SQL code.
- Allows working with data in a familiar object-oriented style.
- Ensures portability across different DBMS.
- Helps avoid errors in SQL queries.
Disadvantages of ORM:
- May generate inefficient queries, reducing performance.
- Complex queries can be difficult to express through ORM.
- An additional layer of abstraction increases complexity and response time.
Example of using ORM in Python with SQLAlchemy:
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import declarative_base, 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()
new_user = User(name='Иван')
session.add(new_user)
session.commit()
user = session.query(User).filter_by(name='Иван').first()
print(user.name) # Иван