postgresql - Postgres : INSERT if does not exist a

我正在使用 Python 写入 postgres 数据库:

sql_string = "INSERT INTO hundred (name,name_slug,status) VALUES ("
sql_string += hundred + ", '" + hundred_slug + "', " + status + ");"
cursor.execute(sql_string)

但由于我的某些行是相同的,我收到以下错误:

psycopg2.IntegrityError: duplicate key value  
  violates unique constraint "hundred_pkey"

如何编写“插入,除非该行已存在”的 SQL 语句?

我见过这样的复杂语句推荐:

IF EXISTS (SELECT * FROM invoices WHERE invoiceid = '12345')
UPDATE invoices SET billed = 'TRUE' WHERE invoiceid = '12345'
ELSE
INSERT INTO invoices (invoiceid, billed) VALUES ('12345', 'TRUE')
END IF

但首先,这是否超出了我的需要,其次,我如何将其中一个作为简单字符串执行?

最佳答案

Postgres 9.5(自 2016-01-07 发布)提供 "upsert"命令,也称为 ON CONFLICT clause to INSERT :

INSERT ... ON CONFLICT DO NOTHING/UPDATE

它解决了您在使用并发操作时可能遇到的许多微妙问题,其他一些答案也提出了这些问题。

关于postgresql - Postgres : INSERT if does not exist already,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4069718/

相关文章:

python - 从另一个 Python 脚本运行 Python 脚本,传入参数

python - 将目录永久添加到 PYTHONPATH?

python - 如何使用 pip 安装 Python MySQLdb 模块?

python - 在 Python 中,何时使用 Dictionary、List 或 Set?

python - 什么是__main__.py?

python - 使用 Python 实现触摸?

python - 在 Python 中比较 float 是否相等的最佳方法是什么?

python - 了解 map 功能

python - 为什么 IoC/DI 在 Python 中不常见?

python - 如何保持键/值与声明的顺序相同?