Python ORM with SqlAlchemy?

Get yourself familiar with ORM in python using SqlAlchemy. 

 

An ORM is Object Relational Mapper which maps with relational database management system to objects. ORM is not dependent on database which is going to be used and gives different objects to access the database to retrieve, insert and manipulate the records. Here we are going to use SqlAlchemy ORM in Python.

To communicate with database, we just use ORM along with Python objects and classes.

Here we are going to use "db.py" a Python files that contains code to import the sqlalchemy liberary and access database. We will use sqlite database for the reference.

To install sqlalchemy, use the command:  pip3 install sqlalchemy

After installation completes, import it into the file where you are going to use it as below:

db.py:

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

### Create database connection
engine = create_engine("sqlite:///test_db.db")
session = sessionmaker(bind=engine){}

## Gives all bunch of table from above database
Base = declarative_base()

class User(Base):

  __tablename__ = "user"

  username = Column(String, primary_key=True)
  password = Column(String)

  def __init__(self, username, password):
    username = self.username
    password = self.password


## Create instance of the user
user = User("Atuf", "password")

## Create a record but doesn't save it to database
session.add(user)

## With this statement it saves into database
session.commit()


## To fetch records from the database table, use below statement

results = session.query(User).all()

for r in results:
  print(r.username)