In the previous chapters of SQLAlchemy ORM, we've learnt a way to claim mapping and create periods. In this chapter, we can discover ways to upload gadgets to the desk.
We have declared Customer class that has been mapped to customers table. We need to claim an item of this magnificence and consistently upload it to the desk via add() technique of consultation object.
c1 = Sales(name = 'Ravi Kumar', address = 'Station Road Nanded', email = 'ravi@gmail.com')
session.add(c1)
Note that this transaction is pending until the same is flushed the usage of dedicate() approach.
session.commit()
Following is the entire script to add a record in clients table −
from sqlalchemy import Column, Integer, String
from sqlalchemy import create_engine
engine = create_engine('sqlite:///sales.db', echo = True)
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Customers(Base):
__tablename__ = 'customers'
id = Column(Integer, primary_key=True)
name = Column(String)
address = Column(String)
email = Column(String)
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind = engine)
session = Session()
c1 = Customers(name = 'Ravi Kumar', address = 'Station Road Nanded', email = 'ravi@gmail.com')
session.add(c1)
session.commit()
To upload a couple of data, we can use add_all() method of the session magnificence.
session.add_all([
Customers(name = 'Komal Pande', address = 'Koti, Hyderabad', email = 'komal@gmail.com'),
Customers(name = 'Rajender Nath', address = 'Sector 40, Gurgaon', email = 'nath@gmail.com'),
Customers(name = 'S.M.Krishna', address = 'Budhwar Peth, Pune', email = 'smk@gmail.com')]
)
session.commit()
Table view of SQLiteStudio shows that the records are constantly delivered in clients table. The following image suggests the result −