【问题标题】:Bulk insert from Python list/dict to Oracle Database using cx_Oracle executemany()使用 cx_Oracle executemany() 从 Python 列表/字典批量插入到 Oracle 数据库
【发布时间】:2019-10-17 12:33:17
【问题描述】:

我正在将 Python 字典中的数据插入 Oracle DB。我使用了游标类中的 executemany()。我收到以下错误:

ORA-01036:非法变量名/编号

另外,当我使用 try/except for executemany() 时,我得到一个额外的错误:

cx_Oracle.DatabaseError:DPI-1010:未连接

环境: Python:3.6.7,Oracle:12c,cx_Oracle:7.1.2,操作系统:Ubuntu

我将字典数据转换为字典列表并将其作为 executemany() 的第二个参数传递,但得到了相同的错误。 这是我的字典列表的样子

    [{'location': 1, 'xxx_id': 917985, 'seq': 758, 'event_time': 
    datetime.datetime(2019, 5, 5, 20, 1, 53), 'event_type': 'xxxx', 'number': 
    123, 'stop': '40305', 'x': None, 'y': None, 'arrival_time': 
    datetime.datetime(2019, 5, 5, 20, 1, 33), 'departure_time': 
    datetime.datetime(2019, 5, 5, 20, 2), 'yyy_id': 529934, 'zzz_id': 59359277}, 
   {'location': 1, 'xxx_id': 917985, 'seq': 759, 'event_time': 
   datetime.datetime(2019, 5, 5, 20, 2, 33), 'event_type': 'xxxx', 'number': 
   123, 'stop': '40301', 'x': None, 'y': None, 'arrival_time': 
   datetime.datetime(2019, 5, 5, 20, 2, 27), 'departure_time': 
   datetime.datetime(2019, 5, 5, 20, 2, 50), 'yyy_id': 529930, 'zzz_id': 59279},

   {.......},
   {.......}
   ]

尝试了 stackoverflow 的其他建议,但没有成功。最接近我的情况是这个。 Insert a list of dictionaries into an SQL table using python

这是我尝试过的代码

    sql_insert = '''INSERT INTO TABLE_NAME (LOCATION, XXX_ID, SEQ, 
    EVENT_TIME, EVENT_TYPE, NUMBER, STOP, X, Y, ARRIVAL_TIME, DEPARTURE_TIME, 
    YYY_ID, ZZZ_ID)
    VALUES(:1, :2, :3, :4, :5, :6, :7, :8, :9, :10, :11, :12, :13)'''

    for k1, v1 in events.items():
        list_events = []
        for k2, v2 in v1.items():
            x = dict(v2)
            # print(x)
            list_events.append(x)
            cursor = connection.cursor()
        try:
            cursor.executemany(sql_insert, list_events)
            connection.commit()
        except cx_Oracle.DatabaseError as e:
            print(e)

我正在尝试插入几千条记录。任何帮助都将不胜感激。

【问题讨论】:

    标签: python database oracle bulkinsert cx-oracle


    【解决方案1】:

    我的一位同事建议使用命名的(例如 values(:location, :peggo_id, ....) 占位符而不是编号占位符,它与命名占位符一起使用。虽然我不确定它是 Oracle 还是cx_Oracle 的东西。另外,如果您在 executemany() 方法中传递字典,命名参数必须与字典中的键名完全相同。

    【讨论】:

      【解决方案2】:

      Efficient and Scalable Batch Statement Execution in Python cx_Oracle

      你想要这样的东西:

      data = [
          (60, "Parent 60"),
          (70, "Parent 70"),
          (80, "Parent 80"),
          (90, "Parent 90"),
          (100, "Parent 100")
      ]
      
      cursor.executemany("""
              insert into ParentTable (ParentId, Description)
              values (:1, :2)""", data)
      

      【讨论】:

        猜你喜欢
        • 2019-05-02
        • 2021-07-17
        • 2021-03-03
        • 2013-08-17
        • 2014-08-30
        • 2018-08-05
        • 2019-03-21
        • 2020-02-06
        • 2023-03-13
        相关资源
        最近更新 更多