如何使用Python将批量插入Oracle数据库?

Jam*_*ams 13 python oracle cx-oracle batch-insert python-2.7

我有一些月度天气数据,我想插入到Oracle数据库表中,但我想在批处理中插入相应的记录,以提高效率.任何人都可以建议我如何在Python中执行此操作?

例如,假设我的表有四个字段:工作站ID,日期和两个值字段.记录由站ID和日期字段(组合键)唯一标识.我必须为每个工作站插入的值将保存在具有X个完整年份数据的列表中,因此,例如,如果有两年的值,则值列表将包含24个值.

我假设如果我想一次插入一个记录,下面就是我这样做的方式:

connection_string = "scott/tiger@testdb"
connection = cx_Oracle.Connection(connection_string)
cursor = cx_Oracle.Cursor(connection)
station_id = 'STATION_1'
start_year = 2000

temps = [ 1, 3, 5, 7, 9, 1, 3, 5, 7, 9, 1, 3 ]
precips = [ 2, 4, 6, 8, 2, 4, 6, 8, 2, 4, 6, 8 ]
number_of_years = len(temps) / 12
for i in range(number_of_years):
    for j in range(12):
        # make a date for the first day of the month
        date_value = datetime.date(start_year + i, j + 1, 1)
        index = (i * 12) + j
        sql_insert = 'insert into my_table (id, date_column, temp, precip) values (%s, %s, %s, %s)', (station_id, date_value, temps[index], precips[index]))
        cursor.execute(sql_insert)
connection.commit()
Run Code Online (Sandbox Code Playgroud)

有没有办法做我正在做的事情,但是以一种执行批量插入的方式来提高效率?顺便说一下,我的经验是使用Java/JDBC/Hibernate,所以如果有人可以提供与Java方法相比的解释/示例,那么它将特别有用.

编辑:也许我需要使用这里描述的cursor.executemany()?

提前感谢任何建议,评论等.

Jam*_*ams 17

这是我提出的似乎运作良好的内容(但如果有办法改进,请发表评论):

# build rows for each date and add to a list of rows we'll use to insert as a batch 
rows = [] 
numberOfYears = endYear - startYear + 1
for i in range(numberOfYears):
    for j in range(12):
        # make a date for the first day of the month
        dateValue = datetime.date(startYear + i, j + 1, 1)
        index = (i * 12) + j
        row = (stationId, dateValue, temps[index], precips[index])
        rows.append(row)

# insert all of the rows as a batch and commit
ip = '192.1.2.3' 
port = 1521
SID = 'my_sid'
dsn = cx_Oracle.makedsn(ip, port, SID)
connection = cx_Oracle.connect('username', 'password', dsn)
cursor = cx_Oracle.Cursor(connection)
cursor.prepare('insert into ' + database_table_name + ' (id, record_date, temp, precip) values (:1, :2, :3, :4)')
cursor.executemany(None, rows)
connection.commit()
cursor.close()
connection.close()
Run Code Online (Sandbox Code Playgroud)


all*_*mix 9

使用Cursor.prepare()Cursor.executemany().

cx_Oracle文档:

Cursor.prepare(声明 [,标签 ])

这可以在调用execute()之前使用,以定义将要执行的语句.完成此操作后,当使用None或与语句相同的字符串对象调用execute()时,将不会执行准备阶段.[...]

Cursor.executemany(声明,参数)

准备一个对数据库执行的语句,然后针对序列参数中找到的所有参数映射或序列执行它.该语句的管理方式与execute()方法管理它的方式相同.

因此,使用上述两个函数,您的代码变为:

connection_string = "scott/tiger@testdb"
connection = cx_Oracle.Connection(connection_string)
cursor = cx_Oracle.Cursor(connection)
station_id = 'STATION_1'
start_year = 2000

temps = [ 1, 3, 5, 7, 9, 1, 3, 5, 7, 9, 1, 3 ]
precips = [ 2, 4, 6, 8, 2, 4, 6, 8, 2, 4, 6, 8 ]
number_of_years = len(temps) / 12

# list comprehension of dates for the first day of the month
date_values = [datetime.date(start_year + i, j + 1, 1) for i in range(number_of_years) for j in range(12)]

# second argument to executemany() should be of the form:
# [{'1': value_a1, '2': value_a2}, {'1': value_b1, '2': value_b2}]
dict_sequence = [{'1': date_values[i], '2': temps[i], '3': precips[i]} for i in range(1, len(temps))]

sql_insert = 'insert into my_table (id, date_column, temp, precip) values (%s, :1, :2, :3)', station_id)
cursor.prepare(sql_insert)
cursor.executemany(None, dict_sequence)
connection.commit()
Run Code Online (Sandbox Code Playgroud)

另请参阅Oracle的Mastering Oracle + Python系列文章.

  • 使用`prepare()`不会给您带来任何好处,只会使您的代码更清晰;两种方法的基础C代码都是相同的。至于您的第一条评论,我更新了我的答案以解决:executemany()将字典序列作为第二个参数。 (2认同)

rag*_*rdl 6

正如评论之一所说,考虑使用INSERT ALL. 据说它会比使用executemany().

例如:

INSERT ALL
  INTO mytable (column1, column2, column_n) VALUES (expr1, expr2, expr_n)
  INTO mytable (column1, column2, column_n) VALUES (expr1, expr2, expr_n)
  INTO mytable (column1, column2, column_n) VALUES (expr1, expr2, expr_n)
SELECT * FROM dual;
Run Code Online (Sandbox Code Playgroud)

http://www.techonthenet.com/oracle/questions/insert_rows.php


zhi*_*fan 5

仅供参考我的测试结果:

我插入 5000 行。每行 3 列。

  1. 运行 insert 5000 次,花费 1.24 分钟。
  2. 与 executemany 一起运行,花费 0.125 秒。
  3. 使用插入所有代码运行:花费 4.08 分钟。

python 代码,它设置了 sql 就像 insert all into t(a,b,c) select :1, :2, :3 from dual union all select :4, :5: :6 from daul ...

设置这个长 sql 的 python 代码,它花费 0.145329 秒。

我在一台非常旧的 sun 机器上测试我的代码。中央处理器:1415 MH。

在第三种情况下,我检查了数据库端,等待事件是“SQL*Net more data from client”。这意味着服务器正在等待来自客户端的更多数据。

第三种方法的结果在没有测试的情况下对我来说是难以置信的。

所以我的简短建议就是使用 executemany。