Object Relational Mapping(ORM) in Python
Object Relational Mapping(ORM) in Python
in python
Introduction:
• Object Relational Mapping is a system of mapping objects to a
database. That means it automates the transfer of data stored in
relational databases tables into objects that are commonly used in
application code.
• When using ORM, we first configure database tables that we will be using.
Then we define classes that will be mapped to them. Modern SQLAlchemy
uses Declarative system to do these tasks.
• A declarative base class is created, which maintains a catalog of classes
and tables. A declarative base class is created with
the declarative_base() function.
• The declarative_base() function is used to create base class. This function
is defined in sqlalchemy.ext.declarative module.
To create declarative base class:
Example:
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
Example: tabledef.py
from sqlalchemy import Column, Integer, String
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
# create a engine
engine =create_engine('mysql+mysqldb://root:@localhost/Sampledb‘)
# create a declarative base class
Base = declarative_base()
class Students(Base):
__tablename__ = 'students'
id = Column(Integer, primary_key=True)
name = Column(String(10))
address = Column(String(10))
email = Column(String(10))
Base.metadata.create_all(engine)