[英]How can I do a batch insert into an Oracle database using Python?
我有一些每月的天气数据,我想插入到 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()
有没有办法做我上面正在做的事情,但是以一种执行批量插入以提高效率的方式? 顺便说一句,我的经验是使用 Java/JDBC/Hibernate,所以如果有人可以给出与 Java 方法相比的解释/示例,那么它会特别有帮助。
编辑:也许我需要使用cursor.executemany()所描述的在这里?
提前感谢您的任何建议、意见等。
这是我想出的似乎效果很好的方法(但如果有改进的方法,请发表评论):
# 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()
使用Cursor.prepare()
和Cursor.executemany()
。
Cursor.prepare
(语句[, tag ])这可以在调用 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()
另请参阅 Oracle 的Mastering Oracle+Python系列文章。
仅供参考我的测试结果:
我插入 5000 行。 每行 3 列。
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 兆赫。
在第三种情况下,我检查了数据库端,等待事件是“SQL*Net more data from client”。 这意味着服务器正在等待来自客户端的更多数据。
第三种方法的结果在没有测试的情况下对我来说是难以置信的。
所以我的简短建议就是使用executemany。
正如其中一条评论所说,考虑使用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;
http://www.techonthenet.com/oracle/questions/insert_rows.php
我将使用联合创建一个大型 SQL 插入语句:
insert into mytable(col1, col2, col3)
select a, b, c from dual union
select d, e, f from dual union
select g, h, i from dual
您可以在 python 中构建字符串并将其作为要执行的语句提供给 oracle。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.