Home > Database > Mysql Tutorial > 在Java中使用Oracle的merge语法

在Java中使用Oracle的merge语法

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-07 17:09:42
Original
1810 people have browsed it

如果不使用Oracle提供的merge语法的话,可能先要上数据库select查询一下看是否存在,然后决定怎么操作,这样的话需要写更多的代码,

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

如果不使用Oracle提供的merge语法的话,可能先要上数据库select查询一下看是否存在,然后决定怎么操作,这样的话需要写更多的代码,

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

使用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();

    }

linux

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template