如何使用 Python 将 BLOB 插入到 Oracle 中?

How to insert a BLOB into Oracle with Python?

我正在尝试使用 cx_Oracle 6.3 将大量 BLOB(每个 2 到 20 MB)插入到 Oracle 12 中。

经过大量谷歌搜索和实验,我得到了以下代码。我是 Python 的新手,想知道:该方法是否有效?有没有更快的方法?

#!/usr/local/bin/python3
import io
import os
import cx_Oracle

pdf = open('hello.pdf', 'rb')
mem_file = io.BytesIO(pdf.read())
mem_file.seek(0, os.SEEK_END)
file_size = mem_file.tell()

con = cx_Oracle.connect("user", "***", "localhost:1512/ORCLPDB1", encoding="UTF-8")

# create table for this example
con.cursor().execute("CREATE TABLE t (id NUMBER, b BLOB) LOB(b) STORE AS SECUREFILE(COMPRESS)");

# prepare cursor
cursor = con.cursor()
my_blob = cursor.var(cx_Oracle.BLOB, file_size)
my_blob.setvalue(0, mem_file.getvalue())

# execute insert
cursor.execute("INSERT INTO t(id, b) VALUES (:my_id, :my_blob)", (1, my_blob))
con.commit()

con.close()

插入一个 EMPTY_BLOB() 并稍后再做一个 UPDATE 怎么样?在插入之前计算 BLOB 的大小是否有必要/有益?

您可以做一些更简单的事情,而且速度也会快得多。请注意,此方法仅在您能够将整个文件内容存储在连续内存中并且当前硬限制为 1 GB 时才有效,即使您有许多 TB 的 RAM 可用!

cursor.execute("insert into t (id, b) values (:my_id, :my_blob)",
        (1, mem_file.getvalue())

插入 empty_blob() 值并返回 LOB 定位器以供以后更新比创建临时 LOB 并插入它(正如您在代码中所做的那样)更快,但直接插入数据甚至更快!