I want to add data to my table using ORM in python

Tags: , ,



I want to add data in my database using ORM, and i am new to ORM in python. I am confused in SQLAlchemy and Flask-SQLAlchemy.”I tried this but don’t know how to proceed further


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

engine = create_engine('sqlite:///C:\Users\52118792\Desktop\test.db')
Base = declarative_base()

class Student(Base):
    __tablename__='Student'
    name=Column(String)
    seq=Column(Integer)

    def __init__(self,name,sequence):
        self.name=name
        self.sequence=sequence

Answer

Flask-SqlAlchemy is commonly used for flask applications, otherwise just plain SqlAlchemy would should be enough.

Flask-SqlAlchemy is a wrapper over SqlAlchemy and gives you following advantages:

  1. A preconfigured scoped session, engine and metadata.
  2. Model base class which is configured declarative base.
  3. Model base class has query attribute attached to it which can be used to query the model.
  4. You don’t need to remove the session at the end of your commit.

Here is how you can use your SqlAlchemy code.

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

engine = create_engine('sqlite:///C:\Users\52118792\Desktop\test.db', echo=True)
Session = sessionmaker(bind=engine)
session = Session()
user = Student("test", 123)
session.add(user)
session.commit()


Source: stackoverflow