【问题标题】:Is there a way to automate UNION ALL insertion?有没有办法自动化 UNION ALL 插入?
【发布时间】:2021-03-14 22:55:55
【问题描述】:

我正在使用 oracle 19c,我正在尝试使用 union all 方法插入。我试图自动化它,我得到了 ORA-00907。
这是我的代码:

def insert(items):
    # items is a list of dicts -> 
    # [{"test": "Test", "Test": "test", "r": "a"}, {"test": "Test", "Test": "test", "s": "a"}...]
    cursor = connection.cursor()
    insertions = []
    for item in items:
        insertions.append(item["test"], item["Test"])  
    query = """INSERT INTO C##USER.RANDOM
SELECT (:1, :2) FROM dual
""" + "\n".join(["UNION ALL SELECT (:{i}, {i+1}) FROM dual" for i in range(3, len(insertions), 2)])
    cursor.execute(query, insertions)

【问题讨论】:

  • 您的代码生成的实际 SQL 是什么?
  • 不知道,据我所知,我无法通过 cx_Oracle 进行检查
  • 如果您的目标(基于您的其他问题)是提高性能,生成数百万条语句,每条语句都有数十万条 union all 语句,数据库每次都必须硬解析,不太可能有益。
  • 为什么select中的值要加括号? Oracle does not allow 你这样做,因为(<some_value>, <some_value>) 不是一个表达式。

标签: python oracle


【解决方案1】:

我相信executemany 是您用例的更好选择。

页面示例:

dataToInsert = [
    (10, 'Parent 10'),
    (20, 'Parent 20'),
    (30, 'Parent 30'),
    (40, 'Parent 40'),
    (50, 'Parent 50')
]
cursor.executemany("insert into ParentTable values (:1, :2)", dataToInsert)

【讨论】:

  • 谢谢!有更好的选择吗?我尝试了 executemany,但对我来说太慢了
  • 看你的@APC链接的其他帖子,你为什么不用SQL*Loader
  • 我不知道它存在,是否可以在python中使用它?
  • 您使用os.system将其作为系统命令调用
【解决方案2】:

如果要有效插入大量生成的测试数据,

不应该使用

INSERT /*+APPEND*/ INTO ... VALUES (...)

related 问题。

请注意,您是逐行插入,因此APPENDhint 在此处无意义并被忽略。

都不你不应该使用大的UNION ALL来选择和绑定成千上万的绑定变量

正如其他人所指出的,这将花费大量的解析时间。

应该使用 one INSERT 语句处理所有要插入的行:

例子

insert /*+ APPEND */ into tab (col1,col2)
select rownum, 'Test'||rownum from dual 
connect by level <= 10000;

请注意,这将在您的表格中填充 10000 行,例如

      COL1 COL2                                        
---------- --------------------------------------------
         1 Test1                                       
         2 Test2                                       
         3 Test3                                       
         4 Test4                                       
         5 Test5 
....

【讨论】:

  • 谢谢!但是Test只是一个例子,每一行都和上一行完全不同,我不能这样生成
猜你喜欢
  • 2021-07-13
  • 1970-01-01
  • 2019-10-15
  • 1970-01-01
  • 2014-01-11
  • 2020-09-30
  • 2011-06-08
  • 2012-06-27
  • 2020-05-02
相关资源
最近更新 更多