首页 > 解决方案 > 在 INSERT INTO 和 ON CONFLICT DO UPDATE 条件后 PostgreSQL “输入结束时的语法错误”

问题描述

我正在尝试在我的 PostgreSQL 数据库上编写一个 UPSERT 代码。

使用

命名参数JdbcTemplate

我收到以下错误消息:

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [


INSERT INTO MY_TABLE
(ID,DATE_TIMESTAMP,ENVIRONMENT,REGION,ORGANIZATION,ARRIVAL_TIMESTAMP,LAST_UPDATED) 
VALUES (?,?,?,?,?,?,?) 
ON CONFLICT (ID, DATE_TIMESTAMP, ENVIRONMENT, REGION)
DO UPDATE

]; nested exception is org.postgresql.util.PSQLException: ERROR: syntax error at end of input] with the root cause

org.postgresql.util.PSQLException: ERROR: syntax error at end of input

查询:

INSERT INTO MY_TABLE
(ID,DATE_TIMESTAMP,ENVIRONMENT,REGION,ORGANIZATION,ARRIVAL_TIMESTAMP,LAST_UPDATED) 
VALUES (:ID,:DATE_TIMESTAMP,:ENVIRONMENT,:REGION,:ORGANIZATION,:ARRIVAL_TIMESTAMP,:LAST_UPDATED) 
ON CONFLICT (ID, DATE_TIMESTAMP, ENVIRONMENT, REGION)
DO UPDATE

我试过没有冲突条件,效果很好。

我试过添加一个 SET 命令,没有用。

我还尝试在 DO UPDATE SET 语句之后使用 setter 我也尝试了您的解决方案,使用 EXCLUDED.COLUMN_NAME 为我要更新的每一列添加一个 SET 语句

我收到以下错误消息:

ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification  Call getNextException to see other errors in the batch.

关于如何解决它的任何建议?

标签: javapostgresqlupsert

解决方案


我找到了解决方案。

错误的原因是我选择的约束。

CONFLICT 条件必须是 CONSTRAINT。例如,主键。

在此处查看完整文档:https ://www.postgresql.org/docs/9.5/sql-insert.html

ON CONFLICT 可用于指定引发唯一约束或排除约束违规错误的替代操作。(见下面的冲突条款。)


推荐阅读