[英]How to write “INSERT IF EXISTS UPDATE” in Oracle using JAVA
I have a ERROR_MSG table which stores error messages with some ids. 我有一个ERROR_MSG表,其中存储带有某些ID的错误消息。 I want to insert error message if id is not present in table and if its present update error message.
如果表中不存在id以及当前更新错误消息,我想插入错误消息。 Inserting using below java JDBC code.
使用下面的Java JDBC代码进行插入。
ID ERROR_MSG
1 ERR1
2 ERR2
3 ERR3
This is my code: 这是我的代码:
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();
}
The simplest solution in JAVA is to check if the row exist. JAVA中最简单的解决方案是检查该行是否存在。
You start by getting a row count for the specific id
you want to insert/update 首先,获取要插入/更新的特定
id
的行数
select count('a') as rowExist from table where id = ?
Then, based on the result, you can easily create your query 然后,根据结果,您可以轻松创建查询
if(rowExist > 0){
query = "update ..";
else
query = "insert ...";
Note that the parameters are probably not in the same order as you expect, you need to create the insert
in the correct order to have the id
at the end (since update
need a where
clause) 请注意,参数的顺序可能与您期望的顺序不同,因此您需要以正确的顺序创建
insert
,以在末尾添加id
(因为update
需要where
子句)
insert into Table (name, birthday, id) values (?, ?, ?)
update Table set name = ?, birthday = ? where id = ?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.