【问题标题】:How to write "INSERT IF EXISTS UPDATE" in Oracle using JAVA如何使用 JAVA 在 Oracle 中编写“INSERT IF EXISTS UPDATE”
【发布时间】:2017-12-11 07:44:14
【问题描述】:

我有一个 ERROR_MSG 表,它存储带有一些 id 的错误消息。如果表中不存在 id 并且它存在更新错误消息,我想插入错误消息。使用下面的 java JDBC 代码插入。

ID ERROR_MSG
1  ERR1
2  ERR2
3  ERR3

这是我的代码:

insertQry = "SQL";
Connection con = null;
PreparedStatement stmt = null;
try {
    con = getDataSource().getConnection();
    stmt = con.prepareStatement(insertQry);
    for(ListingAckNackData errorList: listOfListingERROR) {
        stmt.setLong(1, eqGlobalData.getSrcMsgId());
        stmt.setString(2, errorList.getGliId());
        if (null != errorList.getListingRevisionNo()) {
            stmt.setInt(3, errorList.getListingRevisionNo());
        } else {
            stmt.setNull(3, Types.NULL);
        }
        if (null != errorList.getErrorMessage()) {
            stmt.setString(4, errorList.getErrorMessage());
        } else {
            stmt.setNull(4, Types.NULL);
        }
        stmt.addBatch();
    }
    stmt.executeBatch();
}

【问题讨论】:

  • Oracle: how to UPSERT (update or insert into a table?) 的可能重复项,因为我认为这在 Oracle 的简单 INSERT OR UPDATE 查询中是不可能的。
  • 请注意,answer 在 Java 中提供了一个更简单的解决方案,但会花费一些处理...
  • @AxelH 如何在 JAVA 中使用 if ?
  • 如果”是什么意思?
  • 更新表名 SET val1 = in_val1, val2 = in_val2 WHERE val3 = in_val3; IF ( sql%rowcount = 0 ) THEN INSERT INTO tablename VALUES (in_val1, in_val2, in_val3);万一;如何在上面的 java 代码的字符串 insertQry 中写这个。

标签: java sql oracle


【解决方案1】:

JAVA 中最简单的解决方案是检查该行是否存在。

首先获取要插入/更新的特定 id 的行数

select count('a') as rowExist from table where id = ?

然后,根据结果,您可以轻松创建查询

if(rowExist > 0){
    query = "update ..";
else
    query = "insert ...";

请注意,参数的顺序可能与您期望的不同,您需要以正确的顺序创建 insert 以在末尾添加 id(因为 update 需要 where 子句)

insert into Table (name, birthday, id) values (?, ?, ?)
update Table set name = ?, birthday = ? where id = ?

【讨论】:

  • 因为需要两个 sql,我想要它在一个 sql 中,在 ORACLE 中是不可能的?
  • @ArpanPaliwal 如果您使用通过Callable 从Java 调用的存储过程,这是可能的。为此,请检查副本。这里不需要重写解决方案,因为一切都将在数据库的存储过程中完成。您只需要创建一个Callable 即可调用该过程。
  • 不能使用 store proc 进行小改动,感谢上述解决方案。
  • 使用此解决方案,您必须考虑事务处理。否则,如果存在匹配约束,多个线程可能会插入重复项或遇到异常。
  • 难道没有一个 MERGE 语句可以比在数据库上进行两次点击更好地处理这两个问题吗?
【解决方案2】:

可以根据问题运行数据库语句。只需使用 SQL 命令 MERGE INTO... IF NOT MATCHED INSERT... IF MATCHED UPDATE ... 您将找到完整的示例和文档here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-17
    • 2014-04-27
    • 1970-01-01
    • 2012-06-05
    • 1970-01-01
    • 2014-05-08
    • 2012-09-08
    • 2012-08-08
    相关资源
    最近更新 更多