我有一些每月的天气数据,我想插入一个Oracle数据库表,但我想插入相应的记录在一个批次,以便更有效率.任何人都可以建议我如何在
Python中做这个事情?
例如,我们的表格有四个字段:站号,日期和两个值字段.记录由站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()
有没有办法做我以上的工作,但是为了提高效率,执行批量插入的方式? BTW我的经验是使用Java / JDBC / Hibernate,所以如果有人可以给出与Java方法相比较的解释/示例,那么这将是特别有用的.
编辑:也许我需要使用cursor.executemany(),如here所述?
提前感谢任何建议,意见等.