Postgresql upsert with JDBC parameter markers

Bob*_*ite 4 postgresql jdbc upsert

我有一个 INSERT 语句,当使用参数标记从 JDBC 调用时,它今天可以工作:

INSERT INTO errorqueue as eq (jobname, sourceid, item) VALUES(?,?,?)
Run Code Online (Sandbox Code Playgroud)

在我的 Java 代码中,我绑定了参数:

Connection connection=null;
PreparedStatement stmt=null;
try {

    connection = getConnection();
    stmt = connection.prepareStatement(sqlInsert);

    stmt.setString(1, this.jobName);
    stmt.setString(2, errorItem.getId());
    stmt.setString(3, item.getBody());
    stmt.executeUpdate();
} catch () {
...
}
Run Code Online (Sandbox Code Playgroud)

如果我将其转换为 UPSERT,我正在为如何处理参数而苦苦挣扎:

INSERT INTO errorqueue as eq (jobname, sourceid, item) VALUES(?,?,?) ON CONFLICT (jobname,sourceid) UPDATE eq SET item=? Where jobname=? and sourceid=?;
Run Code Online (Sandbox Code Playgroud)

这是偷偷摸摸的微妙,但在 INSERT 中参数顺序是 (a,b,c) 但在更新中,参数绑定需要是 (c,a,b)

a_h*_*ame 5

您根本不需要on conflict零件中的参数。只需使用set item = excluded.item. 而且您也不需要where更新子句:

INSERT INTO errorqueue as eq 
   (jobname, sourceid, item) 
VALUES(?,?,?) 
ON CONFLICT (jobname,sourceid) 
  UPDATE SET item=exluded.item;
Run Code Online (Sandbox Code Playgroud)

您可以保留 Java 代码,Postgres 将负责匹配正确的行。