
本文介绍如何使用 SQL 的 `ON CONFLICT` 子句来避免在数据库中插入重复记录,并提供一种方法来报告记录是新创建的还是已存在的。通过在 `name` 列上添加唯一索引,我们可以利用 `INSERT ... ON CONFLICT DO NOTHING` 语句,结合后续查询,实现高效的重复记录检查和创建逻辑,并返回操作结果。
在处理数据库操作时,经常需要检查要插入的数据是否已存在。如果存在,则不执行插入操作;如果不存在,则创建新记录。同时,还需要向用户报告操作结果,即记录是新创建的还是已存在的。本文将介绍如何使用 SQL 的 ON CONFLICT 子句,结合唯一索引,来实现这一需求,并提供 Python 代码示例。
核心思想是利用 INSERT ... ON CONFLICT DO NOTHING 语句尝试插入新记录。如果记录已存在(违反唯一约束),则不执行任何操作。然后,通过查询数据库来确定记录是否存在,从而判断是新创建的还是已存在的。
首先,需要在 name 列上创建唯一索引。这将确保 name 列的值在表中是唯一的。
CREATE UNIQUE INDEX ux_product_categories_name ON product_categories (name);
以下是一个 Python 代码示例,使用 SQLAlchemy 和 PostgreSQL 实现 get_or_create 方法:
from sqlalchemy import create_engine, Column, Integer, String, text, inspect, select
from sqlalchemy.orm import Session, Mapped, mapped_column
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class ProductCategory(Base):
__tablename__ = "product_category"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(100), unique=True)
@staticmethod
def get_or_create(name: str, session: Session) -> "ProductCategory":
with session.bind.begin() as conn:
result = conn.execute(
text(
"INSERT INTO product_category (name) "
"VALUES (:name) ON CONFLICT (name) DO NOTHING"
),
dict(name=name),
)
print(
f">>> INFO: {'returning existing category' if result.rowcount == 0 else 'category created'}"
)
return session.scalars(
select(ProductCategory).where(ProductCategory.name == name)
).one()
def __repr__(self):
return f"ProductCategory(id={self.id!r}, name={self.name!r})"
# 示例用法
engine = create_engine("postgresql://user:password@host:port/database") # 替换为你的数据库连接字符串
Base.metadata.create_all(engine)
with Session(engine) as sess:
pc = ProductCategory.get_or_create("shoes", sess)
# >>> INFO: category created
insp = inspect(pc)
print(f"{pc}, persistent={insp.persistent}")
# ProductCategory(id=1, name='shoes'), persistent=True
another_pc = ProductCategory.get_or_create("shoes", sess)
# >>> INFO: returning existing category
print(another_pc)
# ProductCategory(id=1, name='shoes')
print(pc == another_pc)
# True代码解释:
在上面的代码示例中,首先创建了一个名为 "shoes" 的 ProductCategory。然后,再次尝试创建名为 "shoes" 的 ProductCategory。由于 name 列上存在唯一索引,第二次插入操作会因为冲突而失败,但 get_or_create 方法会返回已存在的 ProductCategory 对象。
通过使用 SQL 的 ON CONFLICT 子句和唯一索引,我们可以有效地避免在数据库中插入重复记录,并报告操作结果。这种方法简洁高效,适用于大多数场景。但需要注意并发问题,并根据实际情况选择合适的并发控制机制。
以上就是使用 SQL ON CONFLICT 避免重复记录并报告操作结果的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号