我有一些记录要导入。第一次插入它们就可以了。如果再次尝试导入相同的数据,则会收到org.postgresql.util.PSQLException:错误:重复的键值违反了唯一约束。如果数据相同/或更改,如何使用JDBC更新数据库中的记录,如果是新数据,如何插入?

public void store(Object entity) throws Exception {
    try {
        if (this.updateEntity((XEntity) entity) == 0) {
            this.insertEntity((XEntity) entity);
        }

        ...

    } catch (SQLException sqlEx) {
        ...
    }
}

private int updateEntity(XEntity entity) throws SQLException {
    PreparedStatement prepStmt = this.getUpdatePreparedStmt();
    ...
    return prepStmt.executeUpdate();
}

private void insertEntity(XEntity entity) throws SQLException {
    ...
    this.getInsertPreparedStmt().executeUpdate();
}


现在,此问题已解决。我在下面提供了答案。

最佳答案

您可以尝试使用postgres SQL“ MERGE”或“ REPLACE”

07-24 09:38
查看更多