Cx_Oracle等效于重复密钥更新



现在我有一个名为"Data"的元组列表

[
('171115090000',
Timestamp('2017-11-15 09:00:00'),
'PAIR1',
156.0)
]

我想将此列表插入 Oracle DB,我的代码是

cur.executemany(
            '''INSERT INTO A 
            ("SID","DATE","ATT","VALUE") 
            VALUES(:1,:2,:3,:4)''',Data)

而且效果很好。但是,如果我想在此数据库中添加/替换新记录,则必须创建一个表 B 来放置这些记录,然后合并 A 和 B。

有没有像重复键更新那样的事情,我可以在不创建新表的情况下完成我的工作?

我知道我可以从 A 中选择所有记录,将它们转换为数据帧并在 Python 中合并数据帧,这是一个很好的解决方案吗?

是否有类似重复密钥更新的内容

在Oracle中,它被称为MERGE;请看下面的例子:

开头的表格内容:

SQL> select * From dept;
    DEPTNO DNAME          LOC
---------- -------------- -------------
        10 ACCOUNTING     NEW YORK
        20 RESEARCH       DALLAS
        30 SALES          CHICAGO
        40 OPERATIONS     BOSTON

合并语句:

SQL> merge into dept d
  2    using (select deptno, dname, loc
  3           from (select 10 deptno, 'ACC' dname, 'NY' loc from dual --> already exists, should be updated
  4                 union all
  5                 select 99       , 'NEW DEPT' , 'LONDON' from dual --> doesn't exists, should be inserted
  6                )
  7          ) x
  8  on (d.deptno = x.deptno)
  9  when matched then update set
 10                      d.dname = x.dname,
 11                      d.loc   = x.loc
 12  when not matched then insert (d.deptno, d.dname, d.loc)
 13                        values (x.deptno, x.dname, x.loc);
2 rows merged.

结果:如您所见,现有DEPTNO = 10的值已更新,而新DEPTNO = 99已插入到表中。

SQL> select * From dept;
    DEPTNO DNAME          LOC
---------- -------------- -------------
        10 ACC            NY
        20 RESEARCH       DALLAS
        30 SALES          CHICAGO
        40 OPERATIONS     BOSTON
        99 NEW DEPT       LONDON
SQL>

我不会说Python,所以我不能编写你可能使用的代码,但我希望你能自己做。

最新更新