0

我有一个包含 10 列的Oracle Table名称Consumer,其中 incolumn# 2, 3 and 4构成了它的主键。现在,我想通过Pandas Dataframeusing Insert...On Duplicate Key UpdateSQL 语句插入到这个表中。

首先,我将任何 pandas NaN 或 NaT 转换为 Oracle None,然后将 Dataframe 行转换为元组以进行插入。如果在插入过程中存在主键冲突,那么我只需要更新表中的最后 4 列。

我在这里使用的代码如下:

df1 = df.astype(object).where(df.notnull(), None)
rows = [tuple(x) for x in df1.values]

query = """INSERT INTO CONSUMER VALUES (:1,:2,:3, :4, :5, :6, :7, :8, :9, :10) ON DUPLICATE KEY UPDATE 
                                  DT = VALUES(:7),
                                  AT = VALUES(:8),
                                  OB = VALUES(:9),
                                  UT = VALUES(:10)"""

dbcur.executemany(query, rows)
dbcon.commit()

其中 DT、AT、OB 和 UT 是表中最后 4 列的名称。但这给了我以下错误:

cx_Oracle.DatabaseError: ORA-00933: SQL command not properly ended

有人可以帮我找出并纠正我的代码有什么问题吗?提前谢谢了。

4

1 回答 1

2

INSERT ... ON DUPLICATE KEY UPDATE ...Oracle 中不存在该语法(它特定于 MySQL)。Oracle 的等价物是syntax MERGE对于您的用例,它看起来像:

merge into consumer
using dual
on (col2 = :2 and col3 = :3 and col4 = :4)
when not matched then insert values (:1,:2,:3, :4, :5, :6, :7, :8, :9, :10)
when matched then update set dt = :7, at = :8, ob = :9, ut = :10

注意:您没有告诉主键列的名称是什么,所以我假设col2/3/4. not matched枚举查询子句中插入的所有列也很好。

于 2020-02-13T17:04:14.870 回答