python批量写入oracle

python将数组数据批量写入oracle

from datetime import datetime

import cx_Oracle


if __name__ == '__main__':
    # build rows for each date and add to a list of rows we'll use to insert as a batch
    rows = []

    for i in range(1, 5):
        row = (i * 1, i * 2, i * 3, i * 4, i * 5)
        rows.append(row)

    # insert all of the rows as a batch and commit

    # 测试表
    database_table_name = 'test_load1'

    ip = '你的IP'
    port = 1521
    SID = 'orcl12'
    dsn = cx_Oracle.makedsn(ip, port, SID)

    try:
        # 连接数据库
        connection = cx_Oracle.connect('SCOTT', '123', dsn)
        # 测试连接用——输出数据库版本
        print(connection.version)
        # 获取游标
        cursor = cx_Oracle.Cursor(connection)
        # 写入操作
        cursor.prepare('insert into ' + database_table_name + ' (C1, C2, C3, C4, C5) values (:1, :2, :3, :4, :5)')
        # 执行入库
        cursor.executemany(None, rows)
        connection.commit()
        cursor.close()
        connection.close()

    except Exception as e:
        print('Oracle 写入失败,Exception:{0}'.format(e))
        connection.rollback()
        connection.close()

 

posted @ 2021-06-15 20:32  十点  阅读(951)  评论(0编辑  收藏  举报