在Java中使用Oracle的merge语法

2014-11-24 18:44:04 · 作者: · 浏览: 0

在JAVA开发中通常碰到这样的需求,如果一条数据在表中已经存在,对其做update,如果不存在,将新的数据插入.


同时性能也不好,要来回数据库两次.


使用merge的话则可以一条SQL语句完成.



下面是JAVA代码的示例:(这里简单起见,没有对异常下连接关闭做处理)



private static void testMerge() throws SQLException {


// create table testtb(id int,val varchar2(10))

String sqlstr = "merge into testtb "
+ "using (select as newid, as newval from dual) newData "
+ "ON (testtb.id=newData.newid) "
+ "WHEN NOT MATCHED THEN "
+ "INSERT VALUES (newid,newval) "
+ "WHEN MATCHED THEN " + "UPDATE SET testtb.val=newData.newval";


Connection conn = NONXADBUtil.getConnection("jdbc:oracle:thin:@147.151.100.19:1521:orcl", "user", "pwd");


PreparedStatement sta = conn.prepareStatement(sqlstr);

sta.setInt(1, 1);
sta.setString(2, "new value");

sta.executeUpdate();


sta.close();
conn.commit();
conn.close();


}