SQLAlchemy教程

SQLAlchemy 添加对象

在SQLAlchemy ORM的前几章中,我们已经学习了如何声明映射和创建会话。在本章中,我们将学习如何向表中添加对象。
我们已经声明了映射到客户表的 Customer 类。我们必须声明这个类的一个对象,并通过会话对象的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 的表视图显示记录被持久地添加到客户表中。下图显示了结果-
添加的客户表记录
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4