Error: Key already exists
Error: Key already exists
我正在使用 postgres (psycopg2) 和 python 从 facebook 页面获取信息。我得到一个 json 对象并遍历所有帖子以创建和连接插入查询字符串。就一些用户而言,我收到以下错误:
ERROR: A duplicate key value violates the unique constraint "fb_post_pkey"
DETAIL: Key (id) = (xxx) already exists.
我应该怎么做才能提交查询?我可以从 json 对象中删除重复键吗?
这意味着您的数据库正在正常工作。您的 table 配置为不允许重复。根据您的业务需求,有两种处理方式
try:
# sql insert command here
except IntegrityError:
# tell the user here.
另一种选择是使用数据库通过 ON CONFLICT 子句
优雅地处理这个问题
The optional ON CONFLICT clause specifies an alternative action to
raising a unique violation or exclusion constraint violation error.
For each individual row proposed for insertion, either the insertion
proceeds, or, if an arbiter constraint or index specified by
conflict_target is violated, the alternative conflict_action is taken.
ON CONFLICT DO NOTHING simply avoids inserting a row as its
alternative action. ON CONFLICT DO UPDATE updates the existing row
that conflicts with the row proposed for insertion as its alternative
action.
我正在使用 postgres (psycopg2) 和 python 从 facebook 页面获取信息。我得到一个 json 对象并遍历所有帖子以创建和连接插入查询字符串。就一些用户而言,我收到以下错误:
ERROR: A duplicate key value violates the unique constraint "fb_post_pkey"
DETAIL: Key (id) = (xxx) already exists.
我应该怎么做才能提交查询?我可以从 json 对象中删除重复键吗?
这意味着您的数据库正在正常工作。您的 table 配置为不允许重复。根据您的业务需求,有两种处理方式
try:
# sql insert command here
except IntegrityError:
# tell the user here.
另一种选择是使用数据库通过 ON CONFLICT 子句
优雅地处理这个问题The optional ON CONFLICT clause specifies an alternative action to raising a unique violation or exclusion constraint violation error. For each individual row proposed for insertion, either the insertion proceeds, or, if an arbiter constraint or index specified by conflict_target is violated, the alternative conflict_action is taken. ON CONFLICT DO NOTHING simply avoids inserting a row as its alternative action. ON CONFLICT DO UPDATE updates the existing row that conflicts with the row proposed for insertion as its alternative action.