📜  SQLAlchemy ORM-添加对象

📅  最后修改于: 2020-11-27 07:43:27             🧑  作者: Mango


在SQLAlchemy ORM的前几章中,我们学习了如何声明映射和创建会话。在本章中,我们将学习如何向表中添加对象。

我们声明了已映射到客户表的客户类。我们必须声明一个此类的对象,并通过会话对象的add()方法将其持久地添加到表中。

c1 = Sales(name = 'Ravi Kumar', address = 'Station Road Nanded', email = 'ravi@gmail.com')
session.add(c1)

请注意,此事务将挂起,直到使用commit()方法刷新该事务为止。

session.commit()

以下是在客户表中添加记录的完整脚本-

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()

要添加多个记录,我们可以使用会话类的add_all()方法。

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()

SQLiteStudio的表视图显示记录已永久添加到客户表中。下图显示了结果-

客户表记录已添加