An ORM, or object-relational mapping, is a programming technique that allows a software application to access and manipulate a database. ORMs provide a layer of abstraction between the application and the database, allowing developers to work with objects in their code rather than writing raw SQL queries.
An ORM works by mapping the objects in an application’s code to rows in a database table. When a developer wants to perform an operation on the data in the database, they can do so by calling methods on the ORM-mapped objects, and the ORM will translate these calls into SQL statements that can be executed against the database.
Advantages of using an ORM:
- It allows developers to write code in a high-level, object-oriented language, rather than in the low-level language (SQL etc.) of the database.
- It can improve the performance of database queries by automatically generating optimized and (SQL injection) secure SQL statements.
ORMs are commonly used in modern web development to interact with databases, and there are many different ORM libraries available for various programming languages.
Example – SQLAlchemy (Python ORM library)
from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker engine = create_engine('sqlite:///database.db') Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) age = Column(Integer) Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session() # Create a new user new_user = User(name='Alansh', age=30) session.add(new_user) session.commit() # Query the database users = session.query(User).all() for user in users: print(user.name, user.age) # Update a user user_to_update = session.query(User).filter(User.name == 'Alansh').first() user_to_update.age = 31 session.commit() # Delete a user user_to_delete = session.query(User).filter(User.name == 'Alansh').first() session.delete(user_to_delete) session.commit()
User class is defined with attributes (class’ data members) corresponding to the columns of the
users table in the database. The SQLAlchemy library provides CRUD (create, read, update, and delete) operations for creating, querying, updating, and deleting rows in the table, without actually writing the underlying SQL statements that are used to perform these operations.