使用 cx_Oracle executemany() 从 Python list/dict 批量插入到 Oracle 数据库

Bulk insert from Python list/dict to Oracle Database using cx_Oracle executemany()

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

ORA-01036: 非法变量 name/number

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

cx_Oracle.DatabaseError:DPI-1010:未连接

环境: Python:3.6.7,甲骨文:12c,cx_Oracle:7.1.2,OS: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},

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

尝试了 Whosebug 的其他建议,但没有成功。最接近我的情况是这个。 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)

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

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)

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