java - 在 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.
关于如何解决它的任何建议?
解决方案
我找到了解决方案。
错误的原因是我选择的约束。
CONFLICT 条件必须是 CONSTRAINT。例如,主键。
在此处查看完整文档:https ://www.postgresql.org/docs/9.5/sql-insert.html
ON CONFLICT 可用于指定引发唯一约束或排除约束违规错误的替代操作。(见下面的冲突条款。)
推荐阅读
- spring-integration - Spring Integration 发送消息直到触发自定义事件
- c# - 将对象添加到列表会导致覆盖所有以前的值,尽管在循环中进行了新的实例化
- android - 观察者 onChanged() 不发送最新的值集
- ngxs - 测试 ngxs 状态类
- vim - gVim:基于插入内容的自动注释
- python - Python - 尝试替换包含“”的文本字符串
- c++ - 平面/射线交点与点/平面投影的差异
- r - 在 R 中一次运行多个条件
- logstash - Lagstash 时间戳 dateparseerror
- acumatica - 为什么我的自动编号设置不起作用?