我有一个 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();
}
最佳答案
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 = ?
关于java - 如何使用JAVA在Oracle中写入 "INSERT IF EXISTS UPDATE",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47748372/