SQLAlchemy ORM - 添加对象



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

我们声明了已映射到 customers 表的 Customer 类。我们必须声明此类的对象并通过会话对象的 add() 方法将该对象永久添加到表中。

c1 = Sales(name = 'Ravi Kumar', address = 'Station Road Nanded', email = '[email protected]')
session.add(c1)

请注意,此事务是挂起的,直到使用 commit() 方法刷新事务。

session.commit()

以下是将在 customers 表中添加记录的完整脚本 −

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 = '[email protected]')

session.add(c1)
session.commit()

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

session.add_all([
   Customers(name = 'Komal Pande', address = 'Koti, Hyderabad', email = '[email protected]'), 
   Customers(name = 'Rajender Nath', address = 'Sector 40, Gurgaon', email = '[email protected]'), 
   Customers(name = 'S.M.Krishna', address = 'Budhwar Peth, Pune', email = '[email protected]')]
)

session.commit()

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

Customers Table Records Added
广告