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

发布于 2021-01-29 18:38:24

我有一些每月的天气数据,我想插入到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()?

在此先感谢您的任何建议,评论等。

关注者
0
被浏览
254
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    这是我想出的效果似乎很好的方法(但是如果有改进的方法,请发表评论):

    # 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()
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看