Sqlalchemy 简明教程

SQLAlchemy ORM - Adding Objects

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

In the previous chapters of SQLAlchemy ORM, we have learnt how to declare mapping and create sessions. In this chapter, we will learn how to add objects to the table.

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

We have declared Customer class that has been mapped to customers table. We have to declare an object of this class and persistently add it to the table by add() method of session object.

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

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

Note that this transaction is pending until the same is flushed using commit() method.

session.commit()

以下是向 customers 表中添加记录的完整脚本 -

Following is the complete script to add a record in customers 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()

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

To add multiple records, we can use add_all() method of the session class.

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 表视图显示记录永久添加到 customers 表中。下图显示了结果 -

Table view of SQLiteStudio shows that the records are persistently added in customers table. The following image shows the result −

customers table records added