📜  SQLAlchemy ORM – 添加对象

📅  最后修改于: 2022-05-13 01:54:26.665000             🧑  作者: Mango

SQLAlchemy ORM – 添加对象

在本文中,我们将讨论如何在 SQLAlchemy ORM 中添加对象。

SQLAlchemy 对象关系映射器提供了一种将用户定义的Python类与数据库表和这些类(对象)的实例与其对应表中的行相关联的方法。对于本文,我们将使用 Postgres 数据库。您还可以使用仅内存中的 SQL 数据库。

如果没有,请确保您已正确安装 sqlalchemy,然后安装它:

pip install sqlachemy

例如,您设计了一个API ,用于在数据库中存储和获取用户创建的帖子,有点像 GFG、Instagram 等。这是映射到我们的数据库表“ posts ”的类

Python3
from sqlalchemy import Column, Integer, String, Boolean
from sqlalchemy.ext.declarative import declarative_base
  
# Declare Mapping
Base = declarative_base()
  
# This is the  class which is mapped to "posts" 
# table to our database
class Post(Base):
    __tablename__ = "posts"
    id = Column(Integer, primary_key=True, nullable=False)
    title = Column(String, nullable=False)
    content = Column(String, nullable=False)
    published = Column(Boolean, server_default='true', nullable=False)


Python3
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
  
# Syntax of database url = ":
# //:@ip-address/hostname/
# "
DB_URL = "postgresql://anurag:anurag@localhost/gfg"
  
engine = create_engine(DB_URL)
  
local_session = sessionmaker(autoflush=False, 
                             autocommit=False, bind=engine)
  
# With this we get a session to do whatever
# we want to do
db = local_session()


Python3
# New post created by a user, assumes 
# you get this from the frontend
post = Post(title="GFG Article",
            content="How to add SQL Alchemy objects", 
            published=True)
  
db.add(post)


Python3
# To store the object to the database, 
# otherwise the transaction remains pending
db.commit()
  
# After performing transaction, we should
# always close our connection to the database
# It's a good practice and we must follow it
db.close()
  
print("Successfully added a new post")


Python3
from sqlalchemy import Column, Integer, Boolean, String
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
  
# Declare Mapping
Base = declarative_base()
  
  
# This is the  class which is mapped to "posts" 
# table to our database
class Post(Base):
    __tablename__ = "posts"
    id = Column(Integer, primary_key=True, nullable=False)
    title = Column(String, nullable=False)
    content = Column(String, nullable=False)
    published = Column(Boolean, server_default='true', nullable=False)
  
  
# Syntax of database url = "://
# :@ip-address/hostname/"
DB_URL = "postgresql://anurag:anurag@localhost/gfg"
  
engine = create_engine(DB_URL)
  
local_session = sessionmaker(autoflush=False, autocommit=False, bind=engine)
  
# With this we get a session to do whatever we 
# want to do
db = local_session()
  
# New post created by a user, assumes you get this
# from the frontend
post = Post(title="GFG Article",
            content="How to add SQL Alchemy objects", published=True)
  
db.add(post)
db.commit()
  
# After performing transaction, we should always close
# our connection to the database
db.close()
  
print("Successfully added a new post")


逐步实施

第一步:数据库相关配置

Python3

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
  
# Syntax of database url = ":
# //:@ip-address/hostname/
# "
DB_URL = "postgresql://anurag:anurag@localhost/gfg"
  
engine = create_engine(DB_URL)
  
local_session = sessionmaker(autoflush=False, 
                             autocommit=False, bind=engine)
  
# With this we get a session to do whatever
# we want to do
db = local_session()

第 2 步:添加新对象(帖子)

在这里,我们正在创建一个对象,然后使用 db.add()函数,我们将创建的对象添加到数据库中。

Python3

# New post created by a user, assumes 
# you get this from the frontend
post = Post(title="GFG Article",
            content="How to add SQL Alchemy objects", 
            published=True)
  
db.add(post)

如您所见,在您提交之前,上面的帖子不会保存到数据库中,

Python3

# To store the object to the database, 
# otherwise the transaction remains pending
db.commit()
  
# After performing transaction, we should
# always close our connection to the database
# It's a good practice and we must follow it
db.close()
  
print("Successfully added a new post")

注意:每次进行更改时,请确保您已提交事务,否则事务处于挂起状态。  

提交事务后,您已成功将新对象保存到数据库中,您可以查询数据库中的更改

第三步:查询数据库

在此之下,我们正在验证对象是否成功添加。如果它被添加,那么数据库将显示相同的对象,否则它将不会出现在数据库中。

SELECT * FROM posts;

并且您将所有帖子保存在本地数据库中。

将新对象添加到数据库的完整脚本:

Python3

from sqlalchemy import Column, Integer, Boolean, String
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
  
# Declare Mapping
Base = declarative_base()
  
  
# This is the  class which is mapped to "posts" 
# table to our database
class Post(Base):
    __tablename__ = "posts"
    id = Column(Integer, primary_key=True, nullable=False)
    title = Column(String, nullable=False)
    content = Column(String, nullable=False)
    published = Column(Boolean, server_default='true', nullable=False)
  
  
# Syntax of database url = "://
# :@ip-address/hostname/"
DB_URL = "postgresql://anurag:anurag@localhost/gfg"
  
engine = create_engine(DB_URL)
  
local_session = sessionmaker(autoflush=False, autocommit=False, bind=engine)
  
# With this we get a session to do whatever we 
# want to do
db = local_session()
  
# New post created by a user, assumes you get this
# from the frontend
post = Post(title="GFG Article",
            content="How to add SQL Alchemy objects", published=True)
  
db.add(post)
db.commit()
  
# After performing transaction, we should always close
# our connection to the database
db.close()
  
print("Successfully added a new post")

输出: